home *** CD-ROM | disk | FTP | other *** search
/ Linux Cubed Series 3: Developer Tools / Linux Cubed Series 3 - Developer Tools.iso / utils / text / gawk-3.0 / gawk-3 / gawk-3.0.0.bin / doc / gawk.info < prev    next >
Encoding:
GNU Info File  |  1996-01-15  |  704.4 KB  |  17,941 lines

  1. This is Info file gawk.info, produced by Makeinfo-1.63 from the input
  2. file gawk.texi.
  3.  
  4.    This file documents `awk', a program that you can use to select
  5. particular records in a file and perform operations upon them.
  6.  
  7.    This is Edition 1.0 of `AWK Language Programming', for the 3.0
  8. version of the GNU implementation of AWK.
  9.  
  10.    Copyright (C) 1989, 1991 - 1996 Free Software Foundation, Inc.
  11.  
  12.    Permission is granted to make and distribute verbatim copies of this
  13. manual provided the copyright notice and this permission notice are
  14. preserved on all copies.
  15.  
  16.    Permission is granted to copy and distribute modified versions of
  17. this manual under the conditions for verbatim copying, provided that
  18. the entire resulting derived work is distributed under the terms of a
  19. permission notice identical to this one.
  20.  
  21.    Permission is granted to copy and distribute translations of this
  22. manual into another language, under the above conditions for modified
  23. versions, except that this permission notice may be stated in a
  24. translation approved by the Foundation.
  25.  
  26. 
  27. File: gawk.info,  Node: Top,  Next: Preface,  Prev: (dir),  Up: (dir)
  28.  
  29. General Introduction
  30. ********************
  31.  
  32.    This file documents `awk', a program that you can use to select
  33. particular records in a file and perform operations upon them.
  34.  
  35.    This is Edition 1.0 of `AWK Language Programming',
  36. for the 3.0 version of the GNU implementation
  37. of AWK.
  38.  
  39. * Menu:
  40.  
  41. * Preface::                     What this Info file is about; brief
  42.                                 history and acknowledgements.
  43. * What Is Awk::                 What is the `awk' language; using this
  44.                                 Info file.
  45. * Getting Started::             A basic introduction to using `awk'. How
  46.                                 to run an `awk' program. Command line
  47.                                 syntax.
  48. * One-liners::                  Short, sample `awk' programs.
  49. * Regexp::                      All about matching things using regular
  50.                                 expressions.
  51. * Reading Files::               How to read files and manipulate fields.
  52. * Printing::                    How to print using `awk'.  Describes the
  53.                                 `print' and `printf' statements.
  54.                                 Also describes redirection of output.
  55. * Expressions::                 Expressions are the basic building blocks of
  56.                                 statements.
  57. * Patterns and Actions::        Overviews of patterns and actions.
  58. * Statements::                  The various control statements are described
  59.                                 in detail.
  60. * Built-in Variables::          Built-in Variables
  61. * Arrays::                      The description and use of arrays. Also
  62.                                 includes array-oriented control statements.
  63. * Built-in::                    The built-in functions are summarized here.
  64. * User-defined::                User-defined functions are described in
  65.                                 detail.
  66. * Invoking Gawk::               How to run `gawk'.
  67. * Library Functions::           A Library of `awk' Functions.
  68. * Sample Programs::             Many `awk' programs with complete
  69.                                 explanations.
  70. * Language History::            The evolution of the `awk' language.
  71. * Gawk Summary::                `gawk' Options and Language Summary.
  72. * Installation::                Installing `gawk' under various operating
  73.                                 systems.
  74. * Notes::                       Something about the implementation of
  75.                                 `gawk'.
  76. * Glossary::                    An explanation of some unfamiliar terms.
  77. * Copying::                     Your right to copy and distribute `gawk'.
  78. * Index::                       Concept and Variable Index.
  79.  
  80. * History::                     The history of `gawk' and `awk'.
  81. * Manual History::              Brief history of the GNU project and this
  82.                                 Info file.
  83. * Acknowledgements::            Acknowledgements.
  84. * This Manual::                 Using this Info file. Includes sample
  85.                                 input files that you can use.
  86. * Conventions::                 Typographical Conventions.
  87. * Sample Data Files::           Sample data files for use in the `awk'
  88.                                 programs illustrated in this Info file.
  89. * Names::                       What name to use to find `awk'.
  90. * Running gawk::                How to run `gawk' programs; includes
  91.                                 command line syntax.
  92. * One-shot::                    Running a short throw-away `awk' program.
  93. * Read Terminal::               Using no input files (input from terminal
  94.                                 instead).
  95. * Long::                        Putting permanent `awk' programs in
  96.                                 files.
  97. * Executable Scripts::          Making self-contained `awk' programs.
  98. * Comments::                    Adding documentation to `gawk' programs.
  99. * Very Simple::                 A very simple example.
  100. * Two Rules::                   A less simple one-line example with two rules.
  101. * More Complex::                A more complex example.
  102. * Statements/Lines::            Subdividing or combining statements into
  103.                                 lines.
  104. * Other Features::              Other Features of `awk'.
  105. * When::                        When to use `gawk' and when to use other
  106.                                 things.
  107. * Regexp Usage::                How to Use Regular Expressions.
  108. * Escape Sequences::            How to write non-printing characters.
  109. * Regexp Operators::            Regular Expression Operators.
  110. * GNU Regexp Operators::        Operators specific to GNU software.
  111. * Case-sensitivity::            How to do case-insensitive matching.
  112. * Leftmost Longest::            How much text matches.
  113. * Computed Regexps::            Using Dynamic Regexps.
  114. * Records::                     Controlling how data is split into records.
  115. * Fields::                      An introduction to fields.
  116. * Non-Constant Fields::         Non-constant Field Numbers.
  117. * Changing Fields::             Changing the Contents of a Field.
  118. * Field Separators::            The field separator and how to change it.
  119. * Basic Field Splitting::       How fields are split with single characters or
  120.                                 simple strings.
  121. * Regexp Field Splitting::      Using regexps as the field separator.
  122. * Single Character Fields::     Making each character a separate field.
  123. * Command Line Field Separator:: Setting `FS' from the command line.
  124. * Field Splitting Summary::     Some final points and a summary table.
  125. * Constant Size::               Reading constant width data.
  126. * Multiple Line::               Reading multi-line records.
  127. * Getline::                     Reading files under explicit program control
  128.                                 using the `getline' function.
  129. * Getline Intro::               Introduction to the `getline' function.
  130. * Plain Getline::               Using `getline' with no arguments.
  131. * Getline/Variable::            Using `getline' into a variable.
  132. * Getline/File::                Using `getline' from a file.
  133. * Getline/Variable/File::       Using `getline' into a variable from a
  134.                                 file.
  135. * Getline/Pipe::                Using `getline' from a pipe.
  136. * Getline/Variable/Pipe::       Using `getline' into a variable from a
  137.                                 pipe.
  138. * Getline Summary::             Summary Of `getline' Variants.
  139. * Print::                       The `print' statement.
  140. * Print Examples::              Simple examples of `print' statements.
  141. * Output Separators::           The output separators and how to change them.
  142. * OFMT::                        Controlling Numeric Output With `print'.
  143. * Printf::                      The `printf' statement.
  144. * Basic Printf::                Syntax of the `printf' statement.
  145. * Control Letters::             Format-control letters.
  146. * Format Modifiers::            Format-specification modifiers.
  147. * Printf Examples::             Several examples.
  148. * Redirection::                 How to redirect output to multiple files and
  149.                                 pipes.
  150. * Special Files::               File name interpretation in `gawk'.
  151.                                 `gawk' allows access to inherited file
  152.                                 descriptors.
  153. * Close Files And Pipes::       Closing Input and Output Files and Pipes.
  154. * Constants::                   String, numeric, and regexp constants.
  155. * Scalar Constants::            Numeric and string constants.
  156. * Regexp Constants::            Regular Expression constants.
  157. * Using Constant Regexps::      When and how to use a regexp constant.
  158. * Variables::                   Variables give names to values for later use.
  159. * Using Variables::             Using variables in your programs.
  160. * Assignment Options::          Setting variables on the command line and a
  161.                                 summary of command line syntax. This is an
  162.                                 advanced method of input.
  163. * Conversion::                  The conversion of strings to numbers and vice
  164.                                 versa.
  165. * Arithmetic Ops::              Arithmetic operations (`+', `-',
  166.                                 etc.)
  167. * Concatenation::               Concatenating strings.
  168. * Assignment Ops::              Changing the value of a variable or a field.
  169. * Increment Ops::               Incrementing the numeric value of a variable.
  170. * Truth Values::                What is "true" and what is "false".
  171. * Typing and Comparison::       How variables acquire types, and how this
  172.                                 affects comparison of numbers and strings with
  173.                                 `<', etc.
  174. * Boolean Ops::                 Combining comparison expressions using boolean
  175.                                 operators `||' ("or"), `&&'
  176.                                 ("and") and `!' ("not").
  177. * Conditional Exp::             Conditional expressions select between two
  178.                                 subexpressions under control of a third
  179.                                 subexpression.
  180. * Function Calls::              A function call is an expression.
  181. * Precedence::                  How various operators nest.
  182. * Pattern Overview::            What goes into a pattern.
  183. * Kinds of Patterns::           A list of all kinds of patterns.
  184. * Regexp Patterns::             Using regexps as patterns.
  185. * Expression Patterns::         Any expression can be used as a pattern.
  186. * Ranges::                      Pairs of patterns specify record ranges.
  187. * BEGIN/END::                   Specifying initialization and cleanup rules.
  188. * Using BEGIN/END::             How and why to use BEGIN/END rules.
  189. * I/O And BEGIN/END::           I/O issues in BEGIN/END rules.
  190. * Empty::                       The empty pattern, which matches every record.
  191. * Action Overview::             What goes into an action.
  192. * If Statement::                Conditionally execute some `awk'
  193.                                 statements.
  194. * While Statement::             Loop until some condition is satisfied.
  195. * Do Statement::                Do specified action while looping until some
  196.                                 condition is satisfied.
  197. * For Statement::               Another looping statement, that provides
  198.                                 initialization and increment clauses.
  199. * Break Statement::             Immediately exit the innermost enclosing loop.
  200. * Continue Statement::          Skip to the end of the innermost enclosing
  201.                                 loop.
  202. * Next Statement::              Stop processing the current input record.
  203. * Nextfile Statement::          Stop processing the current file.
  204. * Exit Statement::              Stop execution of `awk'.
  205. * User-modified::               Built-in variables that you change to control
  206.                                 `awk'.
  207. * Auto-set::                    Built-in variables where `awk' gives you
  208.                                 information.
  209. * ARGC and ARGV::               Ways to use `ARGC' and `ARGV'.
  210. * Array Intro::                 Introduction to Arrays
  211. * Reference to Elements::       How to examine one element of an array.
  212. * Assigning Elements::          How to change an element of an array.
  213. * Array Example::               Basic Example of an Array
  214. * Scanning an Array::           A variation of the `for' statement. It
  215.                                 loops through the indices of an array's
  216.                                 existing elements.
  217. * Delete::                      The `delete' statement removes an element
  218.                                 from an array.
  219. * Numeric Array Subscripts::    How to use numbers as subscripts in
  220.                                 `awk'.
  221. * Uninitialized Subscripts::    Using Uninitialized variables as subscripts.
  222. * Multi-dimensional::           Emulating multi-dimensional arrays in
  223.                                 `awk'.
  224. * Multi-scanning::              Scanning multi-dimensional arrays.
  225. * Calling Built-in::            How to call built-in functions.
  226. * Numeric Functions::           Functions that work with numbers, including
  227.                                 `int', `sin' and `rand'.
  228. * String Functions::            Functions for string manipulation, such as
  229.                                 `split', `match', and
  230.                                 `sprintf'.
  231. * I/O Functions::               Functions for files and shell commands.
  232. * Time Functions::              Functions for dealing with time stamps.
  233. * Definition Syntax::           How to write definitions and what they mean.
  234. * Function Example::            An example function definition and what it
  235.                                 does.
  236. * Function Caveats::            Things to watch out for.
  237. * Return Statement::            Specifying the value a function returns.
  238. * Options::                     Command line options and their meanings.
  239. * Other Arguments::             Input file names and variable assignments.
  240. * AWKPATH Variable::            Searching directories for `awk' programs.
  241. * Obsolete::                    Obsolete Options and/or features.
  242. * Undocumented::                Undocumented Options and Features.
  243. * Known Bugs::                  Known Bugs in `gawk'.
  244. * Portability Notes::           What to do if you don't have `gawk'.
  245. * Nextfile Function::           Two implementations of a `nextfile'
  246.                                 function.
  247. * Assert Function::             A function for assertions in `awk'
  248.                                 programs.
  249. * Ordinal Functions::           Functions for using characters as numbers and
  250.                                 vice versa.
  251. * Join Function::               A function to join an array into a string.
  252. * Mktime Function::             A function to turn a date into a timestamp.
  253. * Gettimeofday Function::       A function to get formatted times.
  254. * Filetrans Function::          A function for handling data file transitions.
  255. * Getopt Function::             A function for processing command line
  256.                                 arguments.
  257. * Passwd Functions::            Functions for getting user information.
  258. * Group Functions::             Functions for getting group information.
  259. * Library Names::               How to best name private global variables in
  260.                                 library functions.
  261. * Clones::                      Clones of common utilities.
  262. * Cut Program::                 The `cut' utility.
  263. * Egrep Program::               The `egrep' utility.
  264. * Id Program::                  The `id' utility.
  265. * Split Program::               The `split' utility.
  266. * Tee Program::                 The `tee' utility.
  267. * Uniq Program::                The `uniq' utility.
  268. * Wc Program::                  The `wc' utility.
  269. * Miscellaneous Programs::      Some interesting `awk' programs.
  270. * Dupword Program::             Finding duplicated words in a document.
  271. * Alarm Program::               An alarm clock.
  272. * Translate Program::           A program similar to the `tr' utility.
  273. * Labels Program::              Printing mailing labels.
  274. * Word Sorting::                A program to produce a word usage count.
  275. * History Sorting::             Eliminating duplicate entries from a history
  276.                                 file.
  277. * Extract Program::             Pulling out programs from Texinfo source
  278.                                 files.
  279. * Simple Sed::                  A Simple Stream Editor.
  280. * Igawk Program::               A wrapper for `awk' that includes files.
  281. * V7/SVR3.1::                   The major changes between V7 and System V
  282.                                 Release 3.1.
  283. * SVR4::                        Minor changes between System V Releases 3.1
  284.                                 and 4.
  285. * POSIX::                       New features from the POSIX standard.
  286. * BTL::                         New features from the AT&T Bell Laboratories
  287.                                 version of `awk'.
  288. * POSIX/GNU::                   The extensions in `gawk' not in POSIX
  289.                                 `awk'.
  290. * Command Line Summary::        Recapitulation of the command line.
  291. * Language Summary::            A terse review of the language.
  292. * Variables/Fields::            Variables, fields, and arrays.
  293. * Fields Summary::              Input field splitting.
  294. * Built-in Summary::            `awk''s built-in variables.
  295. * Arrays Summary::              Using arrays.
  296. * Data Type Summary::           Values in `awk' are numbers or strings.
  297. * Rules Summary::               Patterns and Actions, and their component
  298.                                 parts.
  299. * Pattern Summary::             Quick overview of patterns.
  300. * Regexp Summary::              Quick overview of regular expressions.
  301. * Actions Summary::             Quick overview of actions.
  302. * Operator Summary::            `awk' operators.
  303. * Control Flow Summary::        The control statements.
  304. * I/O Summary::                 The I/O statements.
  305. * Printf Summary::              A summary of `printf'.
  306. * Special File Summary::        Special file names interpreted internally.
  307. * Built-in Functions Summary::  Built-in numeric and string functions.
  308. * Time Functions Summary::      Built-in time functions.
  309. * String Constants Summary::    Escape sequences in strings.
  310. * Functions Summary::           Defining and calling functions.
  311. * Historical Features::         Some undocumented but supported "features".
  312. * Gawk Distribution::           What is in the `gawk' distribution.
  313. * Getting::                     How to get the distribution.
  314. * Extracting::                  How to extract the distribution.
  315. * Distribution contents::       What is in the distribution.
  316. * Unix Installation::           Installing `gawk' under various versions
  317.                                 of Unix.
  318. * Quick Installation::          Compiling `gawk' under Unix.
  319. * Configuration Philosophy::    How it's all supposed to work.
  320. * VMS Installation::            Installing `gawk' on VMS.
  321. * VMS Compilation::             How to compile `gawk' under VMS.
  322. * VMS Installation Details::    How to install `gawk' under VMS.
  323. * VMS Running::                 How to run `gawk' under VMS.
  324. * VMS POSIX::                   Alternate instructions for VMS POSIX.
  325. * PC Installation::             Installing and Compiling `gawk' on MS-DOS
  326.                                 and OS/2
  327. * Atari Installation::          Installing `gawk' on the Atari ST.
  328. * Atari Compiling::             Compiling `gawk' on Atari
  329. * Atari Using::                 Running `gawk' on Atari
  330. * Amiga Installation::          Installing `gawk' on an Amiga.
  331. * Bugs::                        Reporting Problems and Bugs.
  332. * Other Versions::              Other freely available `awk'
  333.                                 implementations.
  334. * Compatibility Mode::          How to disable certain `gawk' extensions.
  335. * Additions::                   Making Additions To `gawk'.
  336. * Adding Code::                 Adding code to the main body of `gawk'.
  337. * New Ports::                   Porting `gawk' to a new operating system.
  338. * Future Extensions::           New features that may be implemented one day.
  339. * Improvements::                Suggestions for improvements by volunteers.
  340.  
  341.                   To Miriam, for making me complete.
  342.  
  343.                   To Chana, for the joy you bring us.
  344.  
  345.                 To Rivka, for the exponential increase.
  346.  
  347. 
  348. File: gawk.info,  Node: Preface,  Next: What Is Awk,  Prev: Top,  Up: Top
  349.  
  350. Preface
  351. *******
  352.  
  353.    This Info file teaches you about the `awk' language and how you can
  354. use it effectively.  You should already be familiar with basic system
  355. commands, such as `cat' and `ls',(1) and basic shell facilities, such
  356. as Input/Output (I/O) redirection and pipes.
  357.  
  358.    Implementations of the `awk' language are available for many
  359. different computing environments.  This Info file, while describing the
  360. `awk' language in general, also describes a particular implementation
  361. of `awk' called `gawk' (which stands for "GNU Awk").  `gawk' runs on a
  362. broad range of Unix systems, ranging from 80386 PC-based computers, up
  363. through large scale systems, such as Crays. `gawk' has also been ported
  364. to MS-DOS and OS/2 PC's, Atari and Amiga micro-computers, and VMS.
  365.  
  366. * Menu:
  367.  
  368. * History::                     The history of `gawk' and `awk'.
  369. * Manual History::              Brief history of the GNU project and this
  370.                                 Info file.
  371. * Acknowledgements::            Acknowledgements.
  372.  
  373.    ---------- Footnotes ----------
  374.  
  375.    (1)  These commands are available on POSIX compliant systems, as
  376. well as on traditional Unix based systems. If you are using some other
  377. operating system, you still need to be familiar with the ideas of I/O
  378. redirection and pipes
  379.  
  380. 
  381. File: gawk.info,  Node: History,  Next: Manual History,  Prev: Preface,  Up: Preface
  382.  
  383. History of `awk' and `gawk'
  384. ===========================
  385.  
  386.    The name `awk' comes from the initials of its designers: Alfred V.
  387. Aho, Peter J. Weinberger, and Brian W. Kernighan.  The original version
  388. of `awk' was written in 1977 at AT&T Bell Laboratories.  In 1985 a new
  389. version made the programming language more powerful, introducing
  390. user-defined functions, multiple input streams, and computed regular
  391. expressions.  This new version became generally available with Unix
  392. System V Release 3.1.  The version in System V Release 4 added some new
  393. features and also cleaned up the behavior in some of the "dark corners"
  394. of the language.  The specification for `awk' in the POSIX Command
  395. Language and Utilities standard further clarified the language based on
  396. feedback from both the `gawk' designers, and the original Bell Labs
  397. `awk' designers.
  398.  
  399.    The GNU implementation, `gawk', was written in 1986 by Paul Rubin
  400. and Jay Fenlason, with advice from Richard Stallman.  John Woods
  401. contributed parts of the code as well.  In 1988 and 1989, David
  402. Trueman, with help from Arnold Robbins, thoroughly reworked `gawk' for
  403. compatibility with the newer `awk'.  Current development focuses on bug
  404. fixes, performance improvements, standards compliance, and
  405. occasionally, new features.
  406.  
  407. 
  408. File: gawk.info,  Node: Manual History,  Next: Acknowledgements,  Prev: History,  Up: Preface
  409.  
  410. The GNU Project and This Book
  411. =============================
  412.  
  413.    The Free Software Foundation (FSF) is a non-profit organization
  414. dedicated to the production and distribution of freely distributable
  415. software.  It was founded by Richard M. Stallman, the author of the
  416. original Emacs editor.  GNU Emacs is the most widely used version of
  417. Emacs today.
  418.  
  419.    The GNU project is an on-going effort on the part of the Free
  420. Software Foundation to create a complete, freely distributable, POSIX
  421. compliant computing environment.  (GNU stands for "GNU's not Unix".)
  422. The FSF uses the "GNU General Public License" (or GPL) to ensure that
  423. source code for their software is always available to the end user. A
  424. copy of the GPL is included for your reference (*note GNU GENERAL
  425. PUBLIC LICENSE: Copying.).  The GPL applies to the C language source
  426. code for `gawk'.
  427.  
  428.    As of this writing (1995), the only major component of the GNU
  429. environment still uncompleted is the operating system kernel, and work
  430. proceeds apace on that.  A shell, an editor (Emacs), highly portable
  431. optimizing C, C++, and Objective-C compilers, a symbolic debugger, and
  432. dozens of large and small utilities (such as `gawk'), have all been
  433. completed and are freely available.
  434.  
  435.    Until the GNU operating system is released, the FSF recommends the
  436. use of Linux, a freely distributable, Unix-like operating system for
  437. 80386 and other systems.  There are many books on Linux. One freely
  438. available one is `Linux Installation and Getting Started', by Matt
  439. Welsh.  Many Linux distributions are available, often in computer
  440. stores or bundled on CD-ROM with books about Linux. Also, the FSF
  441. provides a Linux distribution ("Debian"); contact them for more
  442. information.  *Note Getting the `gawk' Distribution: Getting, for the
  443. FSF's contact information.  (There are two other freely available,
  444. Unix-like operating systems for 80386 and other systems, NetBSD and
  445. FreeBSD. Both are based on the 4.4-Lite Berkeley Software Distribution,
  446. and both use recent versions of `gawk' for their versions of `awk'.)
  447.  
  448.    This Info file itself has gone through several previous, preliminary
  449. editions.  I started working on a preliminary draft of `The GAWK
  450. Manual', by Diane Close, Paul Rubin, and Richard Stallman in the fall
  451. of 1988.  It was around 90 pages long, and barely described the
  452. original, "old" version of `awk'. After substantial revision, the first
  453. version of the `The GAWK Manual' to be released was Edition 0.11 Beta in
  454. October of 1989.  The manual then underwent more substantial revision
  455. for Edition 0.13 of December 1991.  David Trueman, Pat Rankin, and
  456. Michal Jaegermann contributed sections of the manual for Edition 0.13.
  457. That edition was published by the FSF as a bound book early in 1992.
  458. Since then there have been several minor revisions, notably Edition
  459. 0.14 of November 1992 that was published by the FSF in January of 1993,
  460. and Edition 0.16 of August 1993.
  461.  
  462.    Edition 1.0 of `AWK Language Programming' represents a significant
  463. re-working of `The GAWK Manual', with much additional material.  The
  464. FSF and I agree that I am now the primary author.  I also felt that it
  465. needed a more descriptive title.
  466.  
  467.    `AWK Language Programming' will undoubtedly continue to evolve.  An
  468. electronic version comes with the `gawk' distribution from the FSF.  If
  469. you find an error in this Info file, please report it!  *Note Reporting
  470. Problems and Bugs: Bugs, for information on submitting problem reports
  471. electronically, or write to me in care of the FSF.
  472.  
  473. 
  474. File: gawk.info,  Node: Acknowledgements,  Prev: Manual History,  Up: Preface
  475.  
  476. Acknowledgements
  477. ================
  478.  
  479.    I would like to acknowledge Richard M. Stallman, for his vision of a
  480. better world, and for his courage in founding the FSF and starting the
  481. GNU project.
  482.  
  483.    The initial draft of `The GAWK Manual' had the following
  484. acknowledgements:
  485.  
  486.      Many people need to be thanked for their assistance in producing
  487.      this manual.  Jay Fenlason contributed many ideas and sample
  488.      programs.  Richard Mlynarik and Robert Chassell gave helpful
  489.      comments on drafts of this manual.  The paper `A Supplemental
  490.      Document for `awk'' by John W.  Pierce of the Chemistry Department
  491.      at UC San Diego, pinpointed several issues relevant both to `awk'
  492.      implementation and to this manual, that would otherwise have
  493.      escaped us.
  494.  
  495.    The following people provided many helpful comments on Edition 0.13
  496. of `The GAWK Manual': Rick Adams, Michael Brennan, Rich Burridge, Diane
  497. Close, Christopher ("Topher") Eliot, Michael Lijewski, Pat Rankin,
  498. Miriam Robbins, and Michal Jaegermann.
  499.  
  500.    The following people provided many helpful comments for Edition 1.0
  501. of `AWK Language Programming': Karl Berry, Michael Brennan, Darrel
  502. Hankerson, Michal Jaegermann, Michael Lijewski, and Miriam Robbins.
  503. Pat Rankin, Michal Jaegermann, Darrel Hankerson and Scott Deifik
  504. updated their respective sections for Edition 1.0.
  505.  
  506.    Robert J. Chassell provided much valuable advice on the use of
  507. Texinfo.  He also deserves special thanks for convincing me *not* to
  508. title this Info file `How To Gawk Politely'.  Karl Berry helped
  509. significantly with the TeX part of Texinfo.
  510.  
  511.    David Trueman deserves special credit; he has done a yeoman job of
  512. evolving `gawk' so that it performs well, and without bugs.  Although
  513. he is no longer involved with `gawk', working with him on this project
  514. was a significant pleasure.
  515.  
  516.    Scott Deifik, Darrel Hankerson, Kai Uwe Rommel, Pat Rankin, and
  517. Michal Jaegermann (in no particular order) are long time members of the
  518. `gawk' "crack portability team."  Without their hard work and help,
  519. `gawk' would not be nearly the fine program it is today.  It has been
  520. and continues to be a pleasure working with this team of fine people.
  521.  
  522.    Jeffrey Friedl provided invaluable help in tracking down a number of
  523. last minute problems with regular expressions in `gawk' 3.0.
  524.  
  525.    David and I would like to thank Brian Kernighan of Bell Labs for
  526. invaluable assistance during the testing and debugging of `gawk', and
  527. for help in clarifying numerous points about the language.  We could
  528. not have done nearly as good a job on either `gawk' or its
  529. documentation without his help.
  530.  
  531.    I would like to thank Marshall and Elaine Hartholz of Seattle, and
  532. Dr.  Bert and Rita Schreiber of Detroit for large amounts of quiet
  533. vacation time in their homes, which allowed me to make significant
  534. progress on this Info file and on `gawk' itself.  Phil Hughes of SSC
  535. contributed in a very important way by loaning me his laptop Linux
  536. system, not once, but twice, allowing me to do a lot of work while away
  537. from home.
  538.  
  539.    Finally, I must thank my wonderful wife, Miriam, for her patience
  540. through the many versions of this project, for her proof-reading, and
  541. for sharing me with the computer.  I would like to thank my parents for
  542. their love, and for the grace with which they raised and educated me.
  543. I also must acknowledge my gratitude to G-d, for the many opportunities
  544. He has sent my way, as well as for the gifts He has given me with which
  545. to take advantage of those opportunities.
  546.  
  547. Arnold Robbins
  548. Atlanta, Georgia
  549. January, 1996
  550.  
  551. 
  552. File: gawk.info,  Node: What Is Awk,  Next: Getting Started,  Prev: Preface,  Up: Top
  553.  
  554. Introduction
  555. ************
  556.  
  557.    If you are like many computer users, you would frequently like to
  558. make changes in various text files wherever certain patterns appear, or
  559. extract data from parts of certain lines while discarding the rest.  To
  560. write a program to do this in a language such as C or Pascal is a
  561. time-consuming inconvenience that may take many lines of code.  The job
  562. may be easier with `awk'.
  563.  
  564.    The `awk' utility interprets a special-purpose programming language
  565. that makes it possible to handle simple data-reformatting jobs with
  566. just a few lines of code.
  567.  
  568.    The GNU implementation of `awk' is called `gawk'; it is fully upward
  569. compatible with the System V Release 4 version of `awk'.  `gawk' is
  570. also upward compatible with the POSIX specification of the `awk'
  571. language.  This means that all properly written `awk' programs should
  572. work with `gawk'.  Thus, we usually don't distinguish between `gawk'
  573. and other `awk' implementations.
  574.  
  575.    Using `awk' you can:
  576.  
  577.    * manage small, personal databases
  578.  
  579.    * generate reports
  580.  
  581.    * validate data
  582.  
  583.    * produce indexes, and perform other document preparation tasks
  584.  
  585.    * even experiment with algorithms that can be adapted later to other
  586.      computer languages
  587.  
  588. * Menu:
  589.  
  590. * This Manual::                 Using this Info file. Includes sample
  591.                                 input files that you can use.
  592. * Conventions::                 Typographical Conventions.
  593. * Sample Data Files::           Sample data files for use in the `awk'
  594.                                 programs illustrated in this Info file.
  595.  
  596. 
  597. File: gawk.info,  Node: This Manual,  Next: Conventions,  Prev: What Is Awk,  Up: What Is Awk
  598.  
  599. Using This Book
  600. ===============
  601.  
  602.    The term `awk' refers to a particular program, and to the language
  603. you use to tell this program what to do.  When we need to be careful,
  604. we call the program "the `awk' utility" and the language "the `awk'
  605. language."  The term `gawk' refers to a version of `awk' developed as
  606. part the GNU project.  The purpose of this Info file is to explain both
  607. the `awk' language and how to run the `awk' utility.
  608.  
  609.    The main purpose of the Info file is to explain the features of
  610. `awk', as defined in the POSIX standard.  It does so in the context of
  611. one particular implementation, `gawk'. While doing so, it will also
  612. attempt to describe important differences between `gawk' and other
  613. `awk' implementations.  Finally, any `gawk' features that are not in
  614. the POSIX standard for `awk' will be noted.
  615.  
  616.    The term "`awk' program" refers to a program written by you in the
  617. `awk' programming language.
  618.  
  619.    *Note Getting Started with `awk': Getting Started, for the bare
  620. essentials you need to know to start using `awk'.
  621.  
  622.    Some useful "one-liners" are included to give you a feel for the
  623. `awk' language (*note Useful One Line Programs: One-liners.).
  624.  
  625.    Many sample `awk' programs have been provided for you (*note A
  626. Library of `awk' Functions: Library Functions.; also *note Practical
  627. `awk' Programs: Sample Programs.).
  628.  
  629.    The entire `awk' language is summarized for quick reference in *Note
  630. `gawk' Summary: Gawk Summary.  Look there if you just need to refresh
  631. your memory about a particular feature.
  632.  
  633.    If you find terms that you aren't familiar with, try looking them up
  634. in the glossary (*note Glossary::.).
  635.  
  636.    Most of the time complete `awk' programs are used as examples, but in
  637. some of the more advanced sections, only the part of the `awk' program
  638. that illustrates the concept being described is shown.
  639.  
  640.    While this Info file is aimed principally at people who have not been
  641. exposed to `awk', there is a lot of information here that even the `awk'
  642. expert should find useful.  In particular, the description of POSIX
  643. `awk', and the example programs in *Note A Library of `awk' Functions:
  644. Library Functions, and *Note Practical `awk' Programs: Sample Programs,
  645. should be of interest.
  646.  
  647. Dark Corners
  648. ------------
  649.  
  650.    Until the POSIX standard (and `The Gawk Manual'), many features of
  651. `awk' were either poorly documented, or not documented at all.
  652. Descriptions of such features (often called "dark corners") are noted
  653. in this Info file with "(d.c.)".  They also appear in the index under
  654. the heading "dark corner."
  655.  
  656. 
  657. File: gawk.info,  Node: Conventions,  Next: Sample Data Files,  Prev: This Manual,  Up: What Is Awk
  658.  
  659. Typographical Conventions
  660. =========================
  661.  
  662.    This Info file is written using Texinfo, the GNU documentation
  663. formatting language.  A single Texinfo source file is used to produce
  664. both the printed and on-line versions of the documentation.  This
  665. section briefly documents the typographical conventions used in Texinfo.
  666.  
  667.    Examples you would type at the command line are preceded by the
  668. common shell primary and secondary prompts, `$' and `>'.  Output from
  669. the command is preceded by the glyph "-|".  This typically represents
  670. the command's standard output.  Error messages, and other output on the
  671. command's standard error, are preceded by the glyph "error-->".  For
  672. example:
  673.  
  674.      $ echo hi on stdout
  675.      -| hi on stdout
  676.      $ echo hello on stderr 1>&2
  677.      error--> hello on stderr
  678.  
  679.    Characters that you type at the keyboard look `like this'.  In
  680. particular, there are special characters called "control characters."
  681. These are characters that you type by holding down both the `CONTROL'
  682. key and another key, at the same time.  For example, a `Control-d' is
  683. typed by first pressing and holding the `CONTROL' key, next pressing
  684. the `d' key, and finally releasing both keys.
  685.  
  686. 
  687. File: gawk.info,  Node: Sample Data Files,  Prev: Conventions,  Up: What Is Awk
  688.  
  689. Data Files for the Examples
  690. ===========================
  691.  
  692.    Many of the examples in this Info file take their input from two
  693. sample data files.  The first, called `BBS-list', represents a list of
  694. computer bulletin board systems together with information about those
  695. systems.  The second data file, called `inventory-shipped', contains
  696. information about shipments on a monthly basis.  In both files, each
  697. line is considered to be one "record".
  698.  
  699.    In the file `BBS-list', each record contains the name of a computer
  700. bulletin board, its phone number, the board's baud rate(s), and a code
  701. for the number of hours it is operational.  An `A' in the last column
  702. means the board operates 24 hours a day.  A `B' in the last column
  703. means the board operates evening and weekend hours, only.  A `C' means
  704. the board operates only on weekends.
  705.  
  706.      aardvark     555-5553     1200/300          B
  707.      alpo-net     555-3412     2400/1200/300     A
  708.      barfly       555-7685     1200/300          A
  709.      bites        555-1675     2400/1200/300     A
  710.      camelot      555-0542     300               C
  711.      core         555-2912     1200/300          C
  712.      fooey        555-1234     2400/1200/300     B
  713.      foot         555-6699     1200/300          B
  714.      macfoo       555-6480     1200/300          A
  715.      sdace        555-3430     2400/1200/300     A
  716.      sabafoo      555-2127     1200/300          C
  717.  
  718.    The second data file, called `inventory-shipped', represents
  719. information about shipments during the year.  Each record contains the
  720. month of the year, the number of green crates shipped, the number of
  721. red boxes shipped, the number of orange bags shipped, and the number of
  722. blue packages shipped, respectively.  There are 16 entries, covering
  723. the 12 months of one year and four months of the next year.
  724.  
  725.      Jan  13  25  15 115
  726.      Feb  15  32  24 226
  727.      Mar  15  24  34 228
  728.      Apr  31  52  63 420
  729.      May  16  34  29 208
  730.      Jun  31  42  75 492
  731.      Jul  24  34  67 436
  732.      Aug  15  34  47 316
  733.      Sep  13  55  37 277
  734.      Oct  29  54  68 525
  735.      Nov  20  87  82 577
  736.      Dec  17  35  61 401
  737.      
  738.      Jan  21  36  64 620
  739.      Feb  26  58  80 652
  740.      Mar  24  75  70 495
  741.      Apr  21  70  74 514
  742.  
  743.    If you are reading this in GNU Emacs using Info, you can copy the
  744. regions of text showing these sample files into your own test files.
  745. This way you can try out the examples shown in the remainder of this
  746. document.  You do this by using the command `M-x write-region' to copy
  747. text from the Info file into a file for use with `awk' (*Note
  748. Miscellaneous File Operations: (emacs)Misc File Ops, for more
  749. information).  Using this information, create your own `BBS-list' and
  750. `inventory-shipped' files, and practice what you learn in this Info
  751. file.
  752.  
  753.    If you are using the stand-alone version of Info, see *Note
  754. Extracting Programs from Texinfo Source Files: Extract Program, for an
  755. `awk' program that will extract these data files from `gawk.texi', the
  756. Texinfo source file for this Info file.
  757.  
  758. 
  759. File: gawk.info,  Node: Getting Started,  Next: One-liners,  Prev: What Is Awk,  Up: Top
  760.  
  761. Getting Started with `awk'
  762. **************************
  763.  
  764.    The basic function of `awk' is to search files for lines (or other
  765. units of text) that contain certain patterns.  When a line matches one
  766. of the patterns, `awk' performs specified actions on that line.  `awk'
  767. keeps processing input lines in this way until the end of the input
  768. files are reached.
  769.  
  770.    Programs in `awk' are different from programs in most other
  771. languages, because `awk' programs are "data-driven"; that is, you
  772. describe the data you wish to work with, and then what to do when you
  773. find it.  Most other languages are "procedural"; you have to describe,
  774. in great detail, every step the program is to take.  When working with
  775. procedural languages, it is usually much harder to clearly describe the
  776. data your program will process.  For this reason, `awk' programs are
  777. often refreshingly easy to both write and read.
  778.  
  779.    When you run `awk', you specify an `awk' "program" that tells `awk'
  780. what to do.  The program consists of a series of "rules".  (It may also
  781. contain "function definitions", an advanced feature which we will
  782. ignore for now.  *Note User-defined Functions: User-defined.)  Each
  783. rule specifies one pattern to search for, and one action to perform
  784. when that pattern is found.
  785.  
  786.    Syntactically, a rule consists of a pattern followed by an action.
  787. The action is enclosed in curly braces to separate it from the pattern.
  788. Rules are usually separated by newlines.  Therefore, an `awk' program
  789. looks like this:
  790.  
  791.      PATTERN { ACTION }
  792.      PATTERN { ACTION }
  793.      ...
  794.  
  795. * Menu:
  796.  
  797. * Names::                       What name to use to find `awk'.
  798. * Running gawk::                How to run `gawk' programs; includes
  799.                                 command line syntax.
  800. * Very Simple::                 A very simple example.
  801. * Two Rules::                   A less simple one-line example with two rules.
  802. * More Complex::                A more complex example.
  803. * Statements/Lines::            Subdividing or combining statements into
  804.                                 lines.
  805. * Other Features::              Other Features of `awk'.
  806. * When::                        When to use `gawk' and when to use other
  807.                                 things.
  808.  
  809. 
  810. File: gawk.info,  Node: Names,  Next: Running gawk,  Prev: Getting Started,  Up: Getting Started
  811.  
  812. A Rose By Any Other Name
  813. ========================
  814.  
  815.    The `awk' language has evolved over the years. Full details are
  816. provided in *Note The Evolution of the `awk' Language: Language History.
  817. The language described in this Info file is often referred to as "new
  818. `awk'."
  819.  
  820.    Because of this, many systems have multiple versions of `awk'.  Some
  821. systems have an `awk' utility that implements the original version of
  822. the `awk' language, and a `nawk' utility for the new version.  Others
  823. have an `oawk' for the "old `awk'" language, and plain `awk' for the
  824. new one.  Still others only have one version, usually the new one.(1)
  825.  
  826.    All in all, this makes it difficult for you to know which version of
  827. `awk' you should run when writing your programs.  The best advice we
  828. can give here is to check your local documentation. Look for `awk',
  829. `oawk', and `nawk', as well as for `gawk'. Chances are, you will have
  830. some version of new `awk' on your system, and that is what you should
  831. use when running your programs.  (Of course, if you're reading this
  832. Info file, chances are good that you have `gawk'!)
  833.  
  834.    Throughout this Info file, whenever we refer to a language feature
  835. that should be available in any complete implementation of POSIX `awk',
  836. we simply use the term `awk'.  When referring to a feature that is
  837. specific to the GNU implementation, we use the term `gawk'.
  838.  
  839.    ---------- Footnotes ----------
  840.  
  841.    (1)  Often, these systems use `gawk' for their `awk' implementation!
  842.  
  843. 
  844. File: gawk.info,  Node: Running gawk,  Next: Very Simple,  Prev: Names,  Up: Getting Started
  845.  
  846. How to Run `awk' Programs
  847. =========================
  848.  
  849.    There are several ways to run an `awk' program.  If the program is
  850. short, it is easiest to include it in the command that runs `awk', like
  851. this:
  852.  
  853.      awk 'PROGRAM' INPUT-FILE1 INPUT-FILE2 ...
  854.  
  855. where PROGRAM consists of a series of patterns and actions, as
  856. described earlier.  (The reason for the single quotes is described
  857. below, in *Note One-shot Throw-away `awk' Programs: One-shot.)
  858.  
  859.    When the program is long, it is usually more convenient to put it in
  860. a file and run it with a command like this:
  861.  
  862.      awk -f PROGRAM-FILE INPUT-FILE1 INPUT-FILE2 ...
  863.  
  864. * Menu:
  865.  
  866. * One-shot::                    Running a short throw-away `awk' program.
  867. * Read Terminal::               Using no input files (input from terminal
  868.                                 instead).
  869. * Long::                        Putting permanent `awk' programs in
  870.                                 files.
  871. * Executable Scripts::          Making self-contained `awk' programs.
  872. * Comments::                    Adding documentation to `gawk' programs.
  873.  
  874. 
  875. File: gawk.info,  Node: One-shot,  Next: Read Terminal,  Prev: Running gawk,  Up: Running gawk
  876.  
  877. One-shot Throw-away `awk' Programs
  878. ----------------------------------
  879.  
  880.    Once you are familiar with `awk', you will often type in simple
  881. programs the moment you want to use them.  Then you can write the
  882. program as the first argument of the `awk' command, like this:
  883.  
  884.      awk 'PROGRAM' INPUT-FILE1 INPUT-FILE2 ...
  885.  
  886. where PROGRAM consists of a series of PATTERNS and ACTIONS, as
  887. described earlier.
  888.  
  889.    This command format instructs the "shell", or command interpreter,
  890. to start `awk' and use the PROGRAM to process records in the input
  891. file(s).  There are single quotes around PROGRAM so that the shell
  892. doesn't interpret any `awk' characters as special shell characters.
  893. They also cause the shell to treat all of PROGRAM as a single argument
  894. for `awk' and allow PROGRAM to be more than one line long.
  895.  
  896.    This format is also useful for running short or medium-sized `awk'
  897. programs from shell scripts, because it avoids the need for a separate
  898. file for the `awk' program.  A self-contained shell script is more
  899. reliable since there are no other files to misplace.
  900.  
  901.    *Note Useful One Line Programs: One-liners, presents several short,
  902. self-contained programs.
  903.  
  904.    As an interesting side point, the command
  905.  
  906.      awk '/foo/' FILES ...
  907.  
  908. is essentially the same as
  909.  
  910.      egrep foo FILES ...
  911.  
  912. 
  913. File: gawk.info,  Node: Read Terminal,  Next: Long,  Prev: One-shot,  Up: Running gawk
  914.  
  915. Running `awk' without Input Files
  916. ---------------------------------
  917.  
  918.    You can also run `awk' without any input files.  If you type the
  919. command line:
  920.  
  921.      awk 'PROGRAM'
  922.  
  923. then `awk' applies the PROGRAM to the "standard input", which usually
  924. means whatever you type on the terminal.  This continues until you
  925. indicate end-of-file by typing `Control-d'.  (On other operating
  926. systems, the end-of-file character may be different.  For example, on
  927. OS/2 and MS-DOS, it is `Control-z'.)
  928.  
  929.    For example, the following program prints a friendly piece of advice
  930. (from Douglas Adams' `The Hitchhiker's Guide to the Galaxy'), to keep
  931. you from worrying about the complexities of computer programming
  932. (`BEGIN' is a feature we haven't discussed yet).
  933.  
  934.      $ awk "BEGIN { print \"Don't Panic!\" }"
  935.      -| Don't Panic!
  936.  
  937.    This program does not read any input.  The `\' before each of the
  938. inner double quotes is necessary because of the shell's quoting rules,
  939. in particular because it mixes both single quotes and double quotes.
  940.  
  941.    This next simple `awk' program emulates the `cat' utility; it copies
  942. whatever you type at the keyboard to its standard output. (Why this
  943. works is explained shortly.)
  944.  
  945.      $ awk '{ print }'
  946.      Now is the time for all good men
  947.      -| Now is the time for all good men
  948.      to come to the aid of their country.
  949.      -| to come to the aid of their country.
  950.      Four score and seven years ago, ...
  951.      -| Four score and seven years ago, ...
  952.      What, me worry?
  953.      -| What, me worry?
  954.      `Control-d'
  955.  
  956. 
  957. File: gawk.info,  Node: Long,  Next: Executable Scripts,  Prev: Read Terminal,  Up: Running gawk
  958.  
  959. Running Long Programs
  960. ---------------------
  961.  
  962.    Sometimes your `awk' programs can be very long.  In this case it is
  963. more convenient to put the program into a separate file.  To tell `awk'
  964. to use that file for its program, you type:
  965.  
  966.      awk -f SOURCE-FILE INPUT-FILE1 INPUT-FILE2 ...
  967.  
  968.    The `-f' instructs the `awk' utility to get the `awk' program from
  969. the file SOURCE-FILE.  Any file name can be used for SOURCE-FILE.  For
  970. example, you could put the program:
  971.  
  972.      BEGIN { print "Don't Panic!" }
  973.  
  974. into the file `advice'.  Then this command:
  975.  
  976.      awk -f advice
  977.  
  978. does the same thing as this one:
  979.  
  980.      awk "BEGIN { print \"Don't Panic!\" }"
  981.  
  982. which was explained earlier (*note Running `awk' without Input Files:
  983. Read Terminal.).  Note that you don't usually need single quotes around
  984. the file name that you specify with `-f', because most file names don't
  985. contain any of the shell's special characters.  Notice that in
  986. `advice', the `awk' program did not have single quotes around it.  The
  987. quotes are only needed for programs that are provided on the `awk'
  988. command line.
  989.  
  990.    If you want to identify your `awk' program files clearly as such,
  991. you can add the extension `.awk' to the file name.  This doesn't affect
  992. the execution of the `awk' program, but it does make "housekeeping"
  993. easier.
  994.  
  995. 
  996. File: gawk.info,  Node: Executable Scripts,  Next: Comments,  Prev: Long,  Up: Running gawk
  997.  
  998. Executable `awk' Programs
  999. -------------------------
  1000.  
  1001.    Once you have learned `awk', you may want to write self-contained
  1002. `awk' scripts, using the `#!' script mechanism.  You can do this on
  1003. many Unix systems(1) (and someday on the GNU system).
  1004.  
  1005.    For example, you could update the file `advice' to look like this:
  1006.  
  1007.      #! /bin/awk -f
  1008.      
  1009.      BEGIN    { print "Don't Panic!" }
  1010.  
  1011. After making this file executable (with the `chmod' utility), you can
  1012. simply type `advice' at the shell, and the system will arrange to run
  1013. `awk' (2) as if you had typed `awk -f advice'.
  1014.  
  1015.      $ advice
  1016.      -| Don't Panic!
  1017.  
  1018. Self-contained `awk' scripts are useful when you want to write a
  1019. program which users can invoke without their having to know that the
  1020. program is written in `awk'.
  1021.  
  1022.    Some older systems do not support the `#!' mechanism. You can get a
  1023. similar effect using a regular shell script.  It would look something
  1024. like this:
  1025.  
  1026.      : The colon ensures execution by the standard shell.
  1027.      awk 'PROGRAM' "$@"
  1028.  
  1029.    Using this technique, it is *vital* to enclose the PROGRAM in single
  1030. quotes to protect it from interpretation by the shell.  If you omit the
  1031. quotes, only a shell wizard can predict the results.
  1032.  
  1033.    The `"$@"' causes the shell to forward all the command line
  1034. arguments to the `awk' program, without interpretation.  The first
  1035. line, which starts with a colon, is used so that this shell script will
  1036. work even if invoked by a user who uses the C shell.  (Not all older
  1037. systems obey this convention, but many do.)
  1038.  
  1039.    ---------- Footnotes ----------
  1040.  
  1041.    (1)  The `#!' mechanism works on Linux systems, Unix systems derived
  1042. from Berkeley Unix, System V Release 4, and some System V Release 3
  1043. systems.
  1044.  
  1045.    (2)  The line beginning with `#!' lists the full file name of an
  1046. interpreter to be run, and an optional initial command line argument to
  1047. pass to that interpreter.  The operating system then runs the
  1048. interpreter with the given argument and the full argument list of the
  1049. executed program.  The first argument in the list is the full file name
  1050. of the `awk' program.  The rest of the argument list will either be
  1051. options to `awk', or data files, or both.
  1052.  
  1053. 
  1054. File: gawk.info,  Node: Comments,  Prev: Executable Scripts,  Up: Running gawk
  1055.  
  1056. Comments in `awk' Programs
  1057. --------------------------
  1058.  
  1059.    A "comment" is some text that is included in a program for the sake
  1060. of human readers; it is not really part of the program.  Comments can
  1061. explain what the program does, and how it works.  Nearly all
  1062. programming languages have provisions for comments, because programs are
  1063. typically hard to understand without their extra help.
  1064.  
  1065.    In the `awk' language, a comment starts with the sharp sign
  1066. character, `#', and continues to the end of the line.  The `#' does not
  1067. have to be the first character on the line. The `awk' language ignores
  1068. the rest of a line following a sharp sign.  For example, we could have
  1069. put the following into `advice':
  1070.  
  1071.      # This program prints a nice friendly message.  It helps
  1072.      # keep novice users from being afraid of the computer.
  1073.      BEGIN    { print "Don't Panic!" }
  1074.  
  1075.    You can put comment lines into keyboard-composed throw-away `awk'
  1076. programs also, but this usually isn't very useful; the purpose of a
  1077. comment is to help you or another person understand the program at a
  1078. later time.
  1079.  
  1080. 
  1081. File: gawk.info,  Node: Very Simple,  Next: Two Rules,  Prev: Running gawk,  Up: Getting Started
  1082.  
  1083. A Very Simple Example
  1084. =====================
  1085.  
  1086.    The following command runs a simple `awk' program that searches the
  1087. input file `BBS-list' for the string of characters: `foo'.  (A string
  1088. of characters is usually called a "string".  The term "string" is
  1089. perhaps based on similar usage in English, such as "a string of
  1090. pearls," or, "a string of cars in a train.")
  1091.  
  1092.      awk '/foo/ { print $0 }' BBS-list
  1093.  
  1094. When lines containing `foo' are found, they are printed, because
  1095. `print $0' means print the current line.  (Just `print' by itself means
  1096. the same thing, so we could have written that instead.)
  1097.  
  1098.    You will notice that slashes, `/', surround the string `foo' in the
  1099. `awk' program.  The slashes indicate that `foo' is a pattern to search
  1100. for.  This type of pattern is called a "regular expression", and is
  1101. covered in more detail later (*note Regular Expressions: Regexp.).  The
  1102. pattern is allowed to match parts of words.  There are single-quotes
  1103. around the `awk' program so that the shell won't interpret any of it as
  1104. special shell characters.
  1105.  
  1106.    Here is what this program prints:
  1107.  
  1108.      $ awk '/foo/ { print $0 }' BBS-list
  1109.      -| fooey        555-1234     2400/1200/300     B
  1110.      -| foot         555-6699     1200/300          B
  1111.      -| macfoo       555-6480     1200/300          A
  1112.      -| sabafoo      555-2127     1200/300          C
  1113.  
  1114.    In an `awk' rule, either the pattern or the action can be omitted,
  1115. but not both.  If the pattern is omitted, then the action is performed
  1116. for *every* input line.  If the action is omitted, the default action
  1117. is to print all lines that match the pattern.
  1118.  
  1119.    Thus, we could leave out the action (the `print' statement and the
  1120. curly braces) in the above example, and the result would be the same:
  1121. all lines matching the pattern `foo' would be printed.  By comparison,
  1122. omitting the `print' statement but retaining the curly braces makes an
  1123. empty action that does nothing; then no lines would be printed.
  1124.  
  1125. 
  1126. File: gawk.info,  Node: Two Rules,  Next: More Complex,  Prev: Very Simple,  Up: Getting Started
  1127.  
  1128. An Example with Two Rules
  1129. =========================
  1130.  
  1131.    The `awk' utility reads the input files one line at a time.  For
  1132. each line, `awk' tries the patterns of each of the rules.  If several
  1133. patterns match then several actions are run, in the order in which they
  1134. appear in the `awk' program.  If no patterns match, then no actions are
  1135. run.
  1136.  
  1137.    After processing all the rules (perhaps none) that match the line,
  1138. `awk' reads the next line (however, *note The `next' Statement: Next
  1139. Statement., and also *note The `nextfile' Statement: Nextfile
  1140. Statement.).  This continues until the end of the file is reached.
  1141.  
  1142.    For example, the `awk' program:
  1143.  
  1144.      /12/  { print $0 }
  1145.      /21/  { print $0 }
  1146.  
  1147. contains two rules.  The first rule has the string `12' as the pattern
  1148. and `print $0' as the action.  The second rule has the string `21' as
  1149. the pattern and also has `print $0' as the action.  Each rule's action
  1150. is enclosed in its own pair of braces.
  1151.  
  1152.    This `awk' program prints every line that contains the string `12'
  1153. *or* the string `21'.  If a line contains both strings, it is printed
  1154. twice, once by each rule.
  1155.  
  1156.    This is what happens if we run this program on our two sample data
  1157. files, `BBS-list' and `inventory-shipped', as shown here:
  1158.  
  1159.      $ awk '/12/ { print $0 }
  1160.      >      /21/ { print $0 }' BBS-list inventory-shipped
  1161.      -| aardvark     555-5553     1200/300          B
  1162.      -| alpo-net     555-3412     2400/1200/300     A
  1163.      -| barfly       555-7685     1200/300          A
  1164.      -| bites        555-1675     2400/1200/300     A
  1165.      -| core         555-2912     1200/300          C
  1166.      -| fooey        555-1234     2400/1200/300     B
  1167.      -| foot         555-6699     1200/300          B
  1168.      -| macfoo       555-6480     1200/300          A
  1169.      -| sdace        555-3430     2400/1200/300     A
  1170.      -| sabafoo      555-2127     1200/300          C
  1171.      -| sabafoo      555-2127     1200/300          C
  1172.      -| Jan  21  36  64 620
  1173.      -| Apr  21  70  74 514
  1174.  
  1175. Note how the line in `BBS-list' beginning with `sabafoo' was printed
  1176. twice, once for each rule.
  1177.  
  1178. 
  1179. File: gawk.info,  Node: More Complex,  Next: Statements/Lines,  Prev: Two Rules,  Up: Getting Started
  1180.  
  1181. A More Complex Example
  1182. ======================
  1183.  
  1184.    Here is an example to give you an idea of what typical `awk'
  1185. programs do.  This example shows how `awk' can be used to summarize,
  1186. select, and rearrange the output of another utility.  It uses features
  1187. that haven't been covered yet, so don't worry if you don't understand
  1188. all the details.
  1189.  
  1190.      ls -lg | awk '$6 == "Nov" { sum += $5 }
  1191.                   END { print sum }'
  1192.  
  1193.    This command prints the total number of bytes in all the files in the
  1194. current directory that were last modified in November (of any year).
  1195. (In the C shell you would need to type a semicolon and then a backslash
  1196. at the end of the first line; in a POSIX-compliant shell, such as the
  1197. Bourne shell or Bash, the GNU Bourne-Again shell, you can type the
  1198. example as shown.)
  1199.  
  1200.    The `ls -lg' part of this example is a system command that gives you
  1201. a listing of the files in a directory, including file size and the date
  1202. the file was last modified. Its output looks like this:
  1203.  
  1204.      -rw-r--r--  1 arnold   user   1933 Nov  7 13:05 Makefile
  1205.      -rw-r--r--  1 arnold   user  10809 Nov  7 13:03 gawk.h
  1206.      -rw-r--r--  1 arnold   user    983 Apr 13 12:14 gawk.tab.h
  1207.      -rw-r--r--  1 arnold   user  31869 Jun 15 12:20 gawk.y
  1208.      -rw-r--r--  1 arnold   user  22414 Nov  7 13:03 gawk1.c
  1209.      -rw-r--r--  1 arnold   user  37455 Nov  7 13:03 gawk2.c
  1210.      -rw-r--r--  1 arnold   user  27511 Dec  9 13:07 gawk3.c
  1211.      -rw-r--r--  1 arnold   user   7989 Nov  7 13:03 gawk4.c
  1212.  
  1213. The first field contains read-write permissions, the second field
  1214. contains the number of links to the file, and the third field
  1215. identifies the owner of the file. The fourth field identifies the group
  1216. of the file.  The fifth field contains the size of the file in bytes.
  1217. The sixth, seventh and eighth fields contain the month, day, and time,
  1218. respectively, that the file was last modified.  Finally, the ninth field
  1219. contains the name of the file.
  1220.  
  1221.    The `$6 == "Nov"' in our `awk' program is an expression that tests
  1222. whether the sixth field of the output from `ls -lg' matches the string
  1223. `Nov'.  Each time a line has the string `Nov' for its sixth field, the
  1224. action `sum += $5' is performed.  This adds the fifth field (the file
  1225. size) to the variable `sum'.  As a result, when `awk' has finished
  1226. reading all the input lines, `sum' is the sum of the sizes of files
  1227. whose lines matched the pattern.  (This works because `awk' variables
  1228. are automatically initialized to zero.)
  1229.  
  1230.    After the last line of output from `ls' has been processed, the
  1231. `END' rule is executed, and the value of `sum' is printed.  In this
  1232. example, the value of `sum' would be 80600.
  1233.  
  1234.    These more advanced `awk' techniques are covered in later sections
  1235. (*note Overview of Actions: Action Overview.).  Before you can move on
  1236. to more advanced `awk' programming, you have to know how `awk'
  1237. interprets your input and displays your output.  By manipulating fields
  1238. and using `print' statements, you can produce some very useful and
  1239. impressive looking reports.
  1240.  
  1241. 
  1242. File: gawk.info,  Node: Statements/Lines,  Next: Other Features,  Prev: More Complex,  Up: Getting Started
  1243.  
  1244. `awk' Statements Versus Lines
  1245. =============================
  1246.  
  1247.    Most often, each line in an `awk' program is a separate statement or
  1248. separate rule, like this:
  1249.  
  1250.      awk '/12/  { print $0 }
  1251.           /21/  { print $0 }' BBS-list inventory-shipped
  1252.  
  1253.    However, `gawk' will ignore newlines after any of the following:
  1254.  
  1255.      ,    {    ?    :    ||    &&    do    else
  1256.  
  1257. A newline at any other point is considered the end of the statement.
  1258. (Splitting lines after `?' and `:' is a minor `gawk' extension.  The
  1259. `?' and `:' referred to here is the three operand conditional
  1260. expression described in *Note Conditional Expressions: Conditional Exp.)
  1261.  
  1262.    If you would like to split a single statement into two lines at a
  1263. point where a newline would terminate it, you can "continue" it by
  1264. ending the first line with a backslash character, `\'.  The backslash
  1265. must be the final character on the line to be recognized as a
  1266. continuation character.  This is allowed absolutely anywhere in the
  1267. statement, even in the middle of a string or regular expression.  For
  1268. example:
  1269.  
  1270.      awk '/This regular expression is too long, so continue it\
  1271.       on the next line/ { print $1 }'
  1272.  
  1273. We have generally not used backslash continuation in the sample programs
  1274. in this Info file.  Since in `gawk' there is no limit on the length of
  1275. a line, it is never strictly necessary; it just makes programs more
  1276. readable.  For this same reason, as well as for clarity, we have kept
  1277. most statements short in the sample programs presented throughout the
  1278. Info file.  Backslash continuation is most useful when your `awk'
  1279. program is in a separate source file, instead of typed in on the
  1280. command line.  You should also note that many `awk' implementations are
  1281. more particular about where you may use backslash continuation. For
  1282. example, they may not allow you to split a string constant using
  1283. backslash continuation.  Thus, for maximal portability of your `awk'
  1284. programs, it is best not to split your lines in the middle of a regular
  1285. expression or a string.
  1286.  
  1287.    *Caution: backslash continuation does not work as described above
  1288. with the C shell.*  Continuation with backslash works for `awk'
  1289. programs in files, and also for one-shot programs *provided* you are
  1290. using a POSIX-compliant shell, such as the Bourne shell or Bash, the
  1291. GNU Bourne-Again shell.  But the C shell (`csh') behaves differently!
  1292. There, you must use two backslashes in a row, followed by a newline.
  1293. Note also that when using the C shell, *every* newline in your awk
  1294. program must be escaped with a backslash. To illustrate:
  1295.  
  1296.      % awk 'BEGIN { \
  1297.      ?   print \\
  1298.      ?       "hello, world" \
  1299.      ? }'
  1300.      -| hello, world
  1301.  
  1302. Here, the `%' and `?' are the C shell's primary and secondary prompts,
  1303. analogous to the standard shell's `$' and `>'.
  1304.  
  1305.    `awk' is a line-oriented language.  Each rule's action has to begin
  1306. on the same line as the pattern.  To have the pattern and action on
  1307. separate lines, you *must* use backslash continuation--there is no
  1308. other way.
  1309.  
  1310.    When `awk' statements within one rule are short, you might want to
  1311. put more than one of them on a line.  You do this by separating the
  1312. statements with a semicolon, `;'.
  1313.  
  1314.    This also applies to the rules themselves.  Thus, the previous
  1315. program could have been written:
  1316.  
  1317.      /12/ { print $0 } ; /21/ { print $0 }
  1318.  
  1319. *Note:* the requirement that rules on the same line must be separated
  1320. with a semicolon was not in the original `awk' language; it was added
  1321. for consistency with the treatment of statements within an action.
  1322.  
  1323. 
  1324. File: gawk.info,  Node: Other Features,  Next: When,  Prev: Statements/Lines,  Up: Getting Started
  1325.  
  1326. Other Features of `awk'
  1327. =======================
  1328.  
  1329.    The `awk' language provides a number of predefined, or built-in
  1330. variables, which your programs can use to get information from `awk'.
  1331. There are other variables your program can set to control how `awk'
  1332. processes your data.
  1333.  
  1334.    In addition, `awk' provides a number of built-in functions for doing
  1335. common computational and string related operations.
  1336.  
  1337.    As we develop our presentation of the `awk' language, we introduce
  1338. most of the variables and many of the functions. They are defined
  1339. systematically in *Note Built-in Variables::, and *Note Built-in
  1340. Functions: Built-in.
  1341.  
  1342. 
  1343. File: gawk.info,  Node: When,  Prev: Other Features,  Up: Getting Started
  1344.  
  1345. When to Use `awk'
  1346. =================
  1347.  
  1348.    You might wonder how `awk' might be useful for you.  Using utility
  1349. programs, advanced patterns, field separators, arithmetic statements,
  1350. and other selection criteria, you can produce much more complex output.
  1351. The `awk' language is very useful for producing reports from large
  1352. amounts of raw data, such as summarizing information from the output of
  1353. other utility programs like `ls'.  (*Note A More Complex Example: More
  1354. Complex.)
  1355.  
  1356.    Programs written with `awk' are usually much smaller than they would
  1357. be in other languages.  This makes `awk' programs easy to compose and
  1358. use.  Often, `awk' programs can be quickly composed at your terminal,
  1359. used once, and thrown away.  Since `awk' programs are interpreted, you
  1360. can avoid the (usually lengthy) compilation part of the typical
  1361. edit-compile-test-debug cycle of software development.
  1362.  
  1363.    Complex programs have been written in `awk', including a complete
  1364. retargetable assembler for eight-bit microprocessors (*note
  1365. Glossary::., for more information) and a microcode assembler for a
  1366. special purpose Prolog computer.  However, `awk''s capabilities are
  1367. strained by tasks of such complexity.
  1368.  
  1369.    If you find yourself writing `awk' scripts of more than, say, a few
  1370. hundred lines, you might consider using a different programming
  1371. language.  Emacs Lisp is a good choice if you need sophisticated string
  1372. or pattern matching capabilities.  The shell is also good at string and
  1373. pattern matching; in addition, it allows powerful use of the system
  1374. utilities.  More conventional languages, such as C, C++, and Lisp, offer
  1375. better facilities for system programming and for managing the complexity
  1376. of large programs.  Programs in these languages may require more lines
  1377. of source code than the equivalent `awk' programs, but they are easier
  1378. to maintain and usually run more efficiently.
  1379.  
  1380. 
  1381. File: gawk.info,  Node: One-liners,  Next: Regexp,  Prev: Getting Started,  Up: Top
  1382.  
  1383. Useful One Line Programs
  1384. ************************
  1385.  
  1386.    Many useful `awk' programs are short, just a line or two.  Here is a
  1387. collection of useful, short programs to get you started.  Some of these
  1388. programs contain constructs that haven't been covered yet.  The
  1389. description of the program will give you a good idea of what is going
  1390. on, but please read the rest of the Info file to become an `awk' expert!
  1391.  
  1392.    Most of the examples use a data file named `data'.  This is just a
  1393. placeholder; if you were to use these programs yourself, you would
  1394. substitute your own file names for `data'.
  1395.  
  1396.    Since you are reading this in Info, each line of the example code is
  1397. enclosed in quotes, to represent text that you would type literally.
  1398. The examples themselves represent shell commands that use single quotes
  1399. to keep the shell from interpreting the contents of the program.  When
  1400. reading the examples, focus on the text between the open and close
  1401. quotes.
  1402.  
  1403. `awk '{ if (length($0) > max) max = length($0) }'
  1404. `     END { print max }' data'
  1405.      This program prints the length of the longest input line.
  1406.  
  1407. `awk 'length($0) > 80' data'
  1408.      This program prints every line that is longer than 80 characters.
  1409.      The sole rule has a relational expression as its pattern, and has
  1410.      no action (so the default action, printing the record, is used).
  1411.  
  1412. `expand data | awk '{ if (x < length()) x = length() }'
  1413. `                   END { print "maximum line length is " x }''
  1414.      This program prints the length of the longest line in `data'.  The
  1415.      input is processed by the `expand' program to change tabs into
  1416.      spaces, so the widths compared are actually the right-margin
  1417.      columns.
  1418.  
  1419. `awk 'NF > 0' data'
  1420.      This program prints every line that has at least one field.  This
  1421.      is an easy way to delete blank lines from a file (or rather, to
  1422.      create a new file similar to the old file but from which the blank
  1423.      lines have been deleted).
  1424.  
  1425. `awk 'BEGIN { for (i = 1; i <= 7; i++)'
  1426. `               print int(101 * rand()) }''
  1427.      This program prints seven random numbers from zero to 100,
  1428.      inclusive.
  1429.  
  1430. `ls -lg FILES | awk '{ x += $5 } ; END { print "total bytes: " x }''
  1431.      This program prints the total number of bytes used by FILES.
  1432.  
  1433. `ls -lg FILES | awk '{ x += $5 }'
  1434. `                 END { print "total K-bytes: " (x + 1023)/1024 }''
  1435.      This program prints the total number of kilobytes used by FILES.
  1436.  
  1437. `awk -F: '{ print $1 }' /etc/passwd | sort'
  1438.      This program prints a sorted list of the login names of all users.
  1439.  
  1440. `awk 'END { print NR }' data'
  1441.      This program counts lines in a file.
  1442.  
  1443. `awk 'NR % 2' data'
  1444.      This program prints the even numbered lines in the data file.  If
  1445.      you were to use the expression `NR % 2 == 1' instead, it would
  1446.      print the odd number lines.
  1447.  
  1448. 
  1449. File: gawk.info,  Node: Regexp,  Next: Reading Files,  Prev: One-liners,  Up: Top
  1450.  
  1451. Regular Expressions
  1452. *******************
  1453.  
  1454.    A "regular expression", or "regexp", is a way of describing a set of
  1455. strings.  Because regular expressions are such a fundamental part of
  1456. `awk' programming, their format and use deserve a separate chapter.
  1457.  
  1458.    A regular expression enclosed in slashes (`/') is an `awk' pattern
  1459. that matches every input record whose text belongs to that set.
  1460.  
  1461.    The simplest regular expression is a sequence of letters, numbers, or
  1462. both.  Such a regexp matches any string that contains that sequence.
  1463. Thus, the regexp `foo' matches any string containing `foo'.  Therefore,
  1464. the pattern `/foo/' matches any input record containing the three
  1465. characters `foo', *anywhere* in the record.  Other kinds of regexps let
  1466. you specify more complicated classes of strings.
  1467.  
  1468. * Menu:
  1469.  
  1470. * Regexp Usage::                How to Use Regular Expressions.
  1471. * Escape Sequences::            How to write non-printing characters.
  1472. * Regexp Operators::            Regular Expression Operators.
  1473. * GNU Regexp Operators::        Operators specific to GNU software.
  1474. * Case-sensitivity::            How to do case-insensitive matching.
  1475. * Leftmost Longest::            How much text matches.
  1476. * Computed Regexps::            Using Dynamic Regexps.
  1477.  
  1478. 
  1479. File: gawk.info,  Node: Regexp Usage,  Next: Escape Sequences,  Prev: Regexp,  Up: Regexp
  1480.  
  1481. How to Use Regular Expressions
  1482. ==============================
  1483.  
  1484.    A regular expression can be used as a pattern by enclosing it in
  1485. slashes.  Then the regular expression is tested against the entire text
  1486. of each record.  (Normally, it only needs to match some part of the
  1487. text in order to succeed.)  For example, this prints the second field
  1488. of each record that contains the three characters `foo' anywhere in it:
  1489.  
  1490.      $ awk '/foo/ { print $2 }' BBS-list
  1491.      -| 555-1234
  1492.      -| 555-6699
  1493.      -| 555-6480
  1494.      -| 555-2127
  1495.  
  1496.    Regular expressions can also be used in matching expressions.  These
  1497. expressions allow you to specify the string to match against; it need
  1498. not be the entire current input record.  The two operators, `~' and
  1499. `!~', perform regular expression comparisons.  Expressions using these
  1500. operators can be used as patterns or in `if', `while', `for', and `do'
  1501. statements.  (*Note Control Statements in Actions: Statements.)
  1502.  
  1503. `EXP ~ /REGEXP/'
  1504.      This is true if the expression EXP (taken as a string) is matched
  1505.      by REGEXP.  The following example matches, or selects, all input
  1506.      records with the upper-case letter `J' somewhere in the first
  1507.      field:
  1508.  
  1509.           $ awk '$1 ~ /J/' inventory-shipped
  1510.           -| Jan  13  25  15 115
  1511.           -| Jun  31  42  75 492
  1512.           -| Jul  24  34  67 436
  1513.           -| Jan  21  36  64 620
  1514.  
  1515.      So does this:
  1516.  
  1517.           awk '{ if ($1 ~ /J/) print }' inventory-shipped
  1518.  
  1519. `EXP !~ /REGEXP/'
  1520.      This is true if the expression EXP (taken as a character string)
  1521.      is *not* matched by REGEXP.  The following example matches, or
  1522.      selects, all input records whose first field *does not* contain
  1523.      the upper-case letter `J':
  1524.  
  1525.           $ awk '$1 !~ /J/' inventory-shipped
  1526.           -| Feb  15  32  24 226
  1527.           -| Mar  15  24  34 228
  1528.           -| Apr  31  52  63 420
  1529.           -| May  16  34  29 208
  1530.           ...
  1531.  
  1532.    When a regexp is written enclosed in slashes, like `/foo/', we call
  1533. it a "regexp constant", much like `5.27' is a numeric constant, and
  1534. `"foo"' is a string constant.
  1535.  
  1536. 
  1537. File: gawk.info,  Node: Escape Sequences,  Next: Regexp Operators,  Prev: Regexp Usage,  Up: Regexp
  1538.  
  1539. Escape Sequences
  1540. ================
  1541.  
  1542.    Some characters cannot be included literally in string constants
  1543. (`"foo"') or regexp constants (`/foo/').  You represent them instead
  1544. with "escape sequences", which are character sequences beginning with a
  1545. backslash (`\').
  1546.  
  1547.    One use of an escape sequence is to include a double-quote character
  1548. in a string constant.  Since a plain double-quote would end the string,
  1549. you must use `\"' to represent an actual double-quote character as a
  1550. part of the string.  For example:
  1551.  
  1552.      $ awk 'BEGIN { print "He said \"hi!\" to her." }'
  1553.      -| He said "hi!" to her.
  1554.  
  1555.    The  backslash character itself is another character that cannot be
  1556. included normally; you write `\\' to put one backslash in the string or
  1557. regexp.  Thus, the string whose contents are the two characters `"' and
  1558. `\' must be written `"\"\\"'.
  1559.  
  1560.    Another use of backslash is to represent unprintable characters such
  1561. as tab or newline.  While there is nothing to stop you from entering
  1562. most unprintable characters directly in a string constant or regexp
  1563. constant, they may look ugly.
  1564.  
  1565.    Here is a table of all the escape sequences used in `awk', and what
  1566. they represent. Unless noted otherwise, all of these escape sequences
  1567. apply to both string constants and regexp constants.
  1568.  
  1569. `\\'
  1570.      A literal backslash, `\'.
  1571.  
  1572. `\a'
  1573.      The "alert" character, `Control-g', ASCII code 7 (BEL).
  1574.  
  1575. `\b'
  1576.      Backspace, `Control-h', ASCII code 8 (BS).
  1577.  
  1578. `\f'
  1579.      Formfeed, `Control-l', ASCII code 12 (FF).
  1580.  
  1581. `\n'
  1582.      Newline, `Control-j', ASCII code 10 (LF).
  1583.  
  1584. `\r'
  1585.      Carriage return, `Control-m', ASCII code 13 (CR).
  1586.  
  1587. `\t'
  1588.      Horizontal tab, `Control-i', ASCII code 9 (HT).
  1589.  
  1590. `\v'
  1591.      Vertical tab, `Control-k', ASCII code 11 (VT).
  1592.  
  1593. `\NNN'
  1594.      The octal value NNN, where NNN are one to three digits between `0'
  1595.      and `7'.  For example, the code for the ASCII ESC (escape)
  1596.      character is `\033'.
  1597.  
  1598. `\xHH...'
  1599.      The hexadecimal value HH, where HH are hexadecimal digits (`0'
  1600.      through `9' and either `A' through `F' or `a' through `f').  Like
  1601.      the same construct in ANSI C, the escape sequence continues until
  1602.      the first non-hexadecimal digit is seen.  However, using more than
  1603.      two hexadecimal digits produces undefined results. (The `\x'
  1604.      escape sequence is not allowed in POSIX `awk'.)
  1605.  
  1606. `\/'
  1607.      A literal slash (necessary for regexp constants only).  You use
  1608.      this when you wish to write a regexp constant that contains a
  1609.      slash. Since the regexp is delimited by slashes, you need to
  1610.      escape the slash that is part of the pattern, in order to tell
  1611.      `awk' to keep processing the rest of the regexp.
  1612.  
  1613. `\"'
  1614.      A literal double-quote (necessary for string constants only).  You
  1615.      use this when you wish to write a string constant that contains a
  1616.      double-quote. Since the string is delimited by double-quotes, you
  1617.      need to escape the quote that is part of the string, in order to
  1618.      tell `awk' to keep processing the rest of the string.
  1619.  
  1620.    In `gawk', there are additional two character sequences that begin
  1621. with backslash that have special meaning in regexps.  *Note Additional
  1622. Regexp Operators Only in `gawk': GNU Regexp Operators.
  1623.  
  1624.    In a string constant, what happens if you place a backslash before
  1625. something that is not one of the characters listed above?  POSIX `awk'
  1626. purposely leaves this case undefined.  There are two choices.
  1627.  
  1628.    * Strip the backslash out.  This is what Unix `awk' and `gawk' both
  1629.      do.  For example, `"a\qc"' is the same as `"aqc"'.
  1630.  
  1631.    * Leave the backslash alone.  Some other `awk' implementations do
  1632.      this.  In such implementations, `"a\qc"' is the same as if you had
  1633.      typed `"a\\qc"'.
  1634.  
  1635.    In a regexp, a backslash before any character that is not in the
  1636. above table, and not listed in *Note Additional Regexp Operators Only
  1637. in `gawk': GNU Regexp Operators, means that the next character should
  1638. be taken literally, even if it would normally be a regexp operator.
  1639. E.g., `/a\+b/' matches the three characters `a+b'.
  1640.  
  1641.    For complete portability, do not use a backslash before any
  1642. character not listed in the table above.
  1643.  
  1644.    Another interesting question arises. Suppose you use an octal or
  1645. hexadecimal escape to represent a regexp metacharacter (*note Regular
  1646. Expression Operators: Regexp Operators.).  Does `awk' treat the
  1647. character as literal character, or as a regexp operator?
  1648.  
  1649.    It turns out that historically, such characters were taken literally
  1650. (d.c.).  However, the POSIX standard indicates that they should be
  1651. treated as real metacharacters, and this is what `gawk' does.  However,
  1652. in compatibility mode (*note Command Line Options: Options.), `gawk'
  1653. treats the characters represented by octal and hexadecimal escape
  1654. sequences literally when used in regexp constants. Thus, `/a\52b/' is
  1655. equivalent to `/a\*b/'.
  1656.  
  1657.    To summarize:
  1658.  
  1659.   1. The escape sequences in the table above are always processed first,
  1660.      for both string constants and regexp constants. This happens very
  1661.      early, as soon as `awk' reads your program.
  1662.  
  1663.   2. `gawk' processes both regexp constants and dynamic regexps (*note
  1664.      Using Dynamic Regexps: Computed Regexps.), for the special
  1665.      operators listed in *Note Additional Regexp Operators Only in
  1666.      `gawk': GNU Regexp Operators.
  1667.  
  1668.   3. A backslash before any other character means to treat that
  1669.      character literally.
  1670.  
  1671. 
  1672. File: gawk.info,  Node: Regexp Operators,  Next: GNU Regexp Operators,  Prev: Escape Sequences,  Up: Regexp
  1673.  
  1674. Regular Expression Operators
  1675. ============================
  1676.  
  1677.    You can combine regular expressions with the following characters,
  1678. called "regular expression operators", or "metacharacters", to increase
  1679. the power and versatility of regular expressions.
  1680.  
  1681.    The escape sequences described in *Note Escape Sequences::, are
  1682. valid inside a regexp.  They are introduced by a `\'.  They are
  1683. recognized and converted into the corresponding real characters as the
  1684. very first step in processing regexps.
  1685.  
  1686.    Here is a table of metacharacters.  All characters that are not
  1687. escape sequences and that are not listed in the table stand for
  1688. themselves.
  1689.  
  1690. `\'
  1691.      This is used to suppress the special meaning of a character when
  1692.      matching.  For example:
  1693.  
  1694.           \$
  1695.  
  1696.      matches the character `$'.
  1697.  
  1698. `^'
  1699.      This matches the beginning of a string.  For example:
  1700.  
  1701.           ^@chapter
  1702.  
  1703.      matches the `@chapter' at the beginning of a string, and can be
  1704.      used to identify chapter beginnings in Texinfo source files.  The
  1705.      `^' is known as an "anchor", since it anchors the pattern to
  1706.      matching only at the beginning of the string.
  1707.  
  1708.      It is important to realize that `^' does not match the beginning of
  1709.      a line embedded in a string.  In this example the condition is not
  1710.      true:
  1711.  
  1712.           if ("line1\nLINE 2" ~ /^L/) ...
  1713.  
  1714. `$'
  1715.      This is similar to `^', but it matches only at the end of a string.
  1716.      For example:
  1717.  
  1718.           p$
  1719.  
  1720.      matches a record that ends with a `p'.  The `$' is also an anchor,
  1721.      and also does not match the end of a line embedded in a string.
  1722.      In this example the condition is not true:
  1723.  
  1724.           if ("line1\nLINE 2" ~ /1$/) ...
  1725.  
  1726. `.'
  1727.      The period, or dot, matches any single character, *including* the
  1728.      newline character.  For example:
  1729.  
  1730.           .P
  1731.  
  1732.      matches any single character followed by a `P' in a string.  Using
  1733.      concatenation we can make a regular expression like `U.A', which
  1734.      matches any three-character sequence that begins with `U' and ends
  1735.      with `A'.
  1736.  
  1737.      In strict POSIX mode (*note Command Line Options: Options.), `.'
  1738.      does not match the NUL character, which is a character with all
  1739.      bits equal to zero.  Otherwise, NUL is just another character.
  1740.      Other versions of `awk' may not be able to match the NUL character.
  1741.  
  1742. `[...]'
  1743.      This is called a "character list".  It matches any *one* of the
  1744.      characters that are enclosed in the square brackets.  For example:
  1745.  
  1746.           [MVX]
  1747.  
  1748.      matches any one of the characters `M', `V', or `X' in a string.
  1749.  
  1750.      Ranges of characters are indicated by using a hyphen between the
  1751.      beginning and ending characters, and enclosing the whole thing in
  1752.      brackets.  For example:
  1753.  
  1754.           [0-9]
  1755.  
  1756.      matches any digit.  Multiple ranges are allowed. E.g., the list
  1757.      `[A-Za-z0-9]' is a common way to express the idea of "all
  1758.      alphanumeric characters."
  1759.  
  1760.      To include one of the characters `\', `]', `-' or `^' in a
  1761.      character list, put a `\' in front of it.  For example:
  1762.  
  1763.           [d\]]
  1764.  
  1765.      matches either `d', or `]'.
  1766.  
  1767.      This treatment of `\' in character lists is compatible with other
  1768.      `awk' implementations, and is also mandated by POSIX.  The regular
  1769.      expressions in `awk' are a superset of the POSIX specification for
  1770.      Extended Regular Expressions (EREs).  POSIX EREs are based on the
  1771.      regular expressions accepted by the traditional `egrep' utility.
  1772.  
  1773.      "Character classes" are a new feature introduced in the POSIX
  1774.      standard.  A character class is a special notation for describing
  1775.      lists of characters that have a specific attribute, but where the
  1776.      actual characters themselves can vary from country to country
  1777.      and/or from character set to character set.  For example, the
  1778.      notion of what is an alphabetic character differs in the USA and
  1779.      in France.
  1780.  
  1781.      A character class is only valid in a regexp *inside* the brackets
  1782.      of a character list.  Character classes consist of `[:', a keyword
  1783.      denoting the class, and `:]'.  Here are the character classes
  1784.      defined by the POSIX standard.
  1785.  
  1786.     `[:alnum:]'
  1787.           Alphanumeric characters.
  1788.  
  1789.     `[:alpha:]'
  1790.           Alphabetic characters.
  1791.  
  1792.     `[:blank:]'
  1793.           Space and tab characters.
  1794.  
  1795.     `[:cntrl:]'
  1796.           Control characters.
  1797.  
  1798.     `[:digit:]'
  1799.           Numeric characters.
  1800.  
  1801.     `[:graph:]'
  1802.           Characters that are printable and are also visible.  (A space
  1803.           is printable, but not visible, while an `a' is both.)
  1804.  
  1805.     `[:lower:]'
  1806.           Lower-case alphabetic characters.
  1807.  
  1808.     `[:print:]'
  1809.           Printable characters (characters that are not control
  1810.           characters.)
  1811.  
  1812.     `[:punct:]'
  1813.           Punctuation characters (characters that are not letter,
  1814.           digits, control characters, or space characters).
  1815.  
  1816.     `[:space:]'
  1817.           Space characters (such as space, tab, and formfeed, to name a
  1818.           few).
  1819.  
  1820.     `[:upper:]'
  1821.           Upper-case alphabetic characters.
  1822.  
  1823.     `[:xdigit:]'
  1824.           Characters that are hexadecimal digits.
  1825.  
  1826.      For example, before the POSIX standard, to match alphanumeric
  1827.      characters, you had to write `/[A-Za-z0-9]/'.  If your character
  1828.      set had other alphabetic characters in it, this would not match
  1829.      them.  With the POSIX character classes, you can write
  1830.      `/[[:alnum:]]/', and this will match *all* the alphabetic and
  1831.      numeric characters in your character set.
  1832.  
  1833.      Two additional special sequences can appear in character lists.
  1834.      These apply to non-ASCII character sets, which can have single
  1835.      symbols (called "collating elements") that are represented with
  1836.      more than one character, as well as several characters that are
  1837.      equivalent for "collating", or sorting, purposes.  (E.g., in
  1838.      French, a plain "e" and a grave-accented "e" are equivalent.)
  1839.  
  1840.     Collating Symbols
  1841.           A "collating symbol" is a multi-character collating element
  1842.           enclosed in `[.' and `.]'.  For example, if `ch' is a
  1843.           collating element, then `[[.ch.]]' is a regexp that matches
  1844.           this collating element, while `[ch]' is a regexp that matches
  1845.           either `c' or `h'.
  1846.  
  1847.     Equivalence Classes
  1848.           An "equivalence class" is a list of equivalent characters
  1849.           enclosed in `[=' and `=]'.  Because Info files use plain
  1850.           ASCII characters, it is not possible to present a realistic
  1851.           equivalence class example here.
  1852.  
  1853.      These features are very valuable in non-English speaking locales.
  1854.  
  1855.      *Caution:* The library functions that `gawk' uses for regular
  1856.      expression matching currently only recognize POSIX character
  1857.      classes; they do not recognize collating symbols or equivalence
  1858.      classes.
  1859.  
  1860. `[^ ...]'
  1861.      This is a "complemented character list".  The first character after
  1862.      the `[' *must* be a `^'.  It matches any characters *except* those
  1863.      in the square brackets, or newline.  For example:
  1864.  
  1865.           [^0-9]
  1866.  
  1867.      matches any character that is not a digit.
  1868.  
  1869. `|'
  1870.      This is the "alternation operator", and it is used to specify
  1871.      alternatives.  For example:
  1872.  
  1873.           ^P|[0-9]
  1874.  
  1875.      matches any string that matches either `^P' or `[0-9]'.  This
  1876.      means it matches any string that starts with `P' or contains a
  1877.      digit.
  1878.  
  1879.      The alternation applies to the largest possible regexps on either
  1880.      side.  In other words, `|' has the lowest precedence of all the
  1881.      regular expression operators.
  1882.  
  1883. `(...)'
  1884.      Parentheses are used for grouping in regular expressions as in
  1885.      arithmetic.  They can be used to concatenate regular expressions
  1886.      containing the alternation operator, `|'.  For example,
  1887.      `@(samp|code)\{[^}]+\}' matches both `@code{foo}' and
  1888.      `@samp{bar}'. (These are Texinfo formatting control sequences.)
  1889.  
  1890. `*'
  1891.      This symbol means that the preceding regular expression is to be
  1892.      repeated as many times as necessary to find a match.  For example:
  1893.  
  1894.           ph*
  1895.  
  1896.      applies the `*' symbol to the preceding `h' and looks for matches
  1897.      of one `p' followed by any number of `h's.  This will also match
  1898.      just `p' if no `h's are present.
  1899.  
  1900.      The `*' repeats the *smallest* possible preceding expression.
  1901.      (Use parentheses if you wish to repeat a larger expression.)  It
  1902.      finds as many repetitions as possible.  For example:
  1903.  
  1904.           awk '/\(c[ad][ad]*r x\)/ { print }' sample
  1905.  
  1906.      prints every record in `sample' containing a string of the form
  1907.      `(car x)', `(cdr x)', `(cadr x)', and so on.  Notice the escaping
  1908.      of the parentheses by preceding them with backslashes.
  1909.  
  1910. `+'
  1911.      This symbol is similar to `*', but the preceding expression must be
  1912.      matched at least once.  This means that:
  1913.  
  1914.           wh+y
  1915.  
  1916.      would match `why' and `whhy' but not `wy', whereas `wh*y' would
  1917.      match all three of these strings.  This is a simpler way of
  1918.      writing the last `*' example:
  1919.  
  1920.           awk '/\(c[ad]+r x\)/ { print }' sample
  1921.  
  1922. `?'
  1923.      This symbol is similar to `*', but the preceding expression can be
  1924.      matched either once or not at all.  For example:
  1925.  
  1926.           fe?d
  1927.  
  1928.      will match `fed' and `fd', but nothing else.
  1929.  
  1930. `{N}'
  1931. `{N,}'
  1932. `{N,M}'
  1933.      One or two numbers inside braces denote an "interval expression".
  1934.      If there is one number in the braces, the preceding regexp is
  1935.      repeated N times.  If there are two numbers separated by a comma,
  1936.      the preceding regexp is repeated N to M times.  If there is one
  1937.      number followed by a comma, then the preceding regexp is repeated
  1938.      at least N times.
  1939.  
  1940.     `wh{3}y'
  1941.           matches `whhhy' but not `why' or `whhhhy'.
  1942.  
  1943.     `wh{3,5}y'
  1944.           matches `whhhy' or `whhhhy' or `whhhhhy', only.
  1945.  
  1946.     `wh{2,}y'
  1947.           matches `whhy' or `whhhy', and so on.
  1948.  
  1949.      Interval expressions were not traditionally available in `awk'.
  1950.      As part of the POSIX standard they were added, to make `awk' and
  1951.      `egrep' consistent with each other.
  1952.  
  1953.      However, since old programs may use `{' and `}' in regexp
  1954.      constants, by default `gawk' does *not* match interval expressions
  1955.      in regexps.  If either `--posix' or `--re-interval' are specified
  1956.      (*note Command Line Options: Options.), then interval expressions
  1957.      are allowed in regexps.
  1958.  
  1959.    In regular expressions, the `*', `+', and `?' operators, as well as
  1960. the braces `{' and `}', have the highest precedence, followed by
  1961. concatenation, and finally by `|'.  As in arithmetic, parentheses can
  1962. change how operators are grouped.
  1963.  
  1964.    If `gawk' is in compatibility mode (*note Command Line Options:
  1965. Options.), character classes and interval expressions are not available
  1966. in regular expressions.
  1967.  
  1968.    The next node discusses the GNU-specific regexp operators, and
  1969. provides more detail concerning how command line options affect the way
  1970. `gawk' interprets the characters in regular expressions.
  1971.  
  1972. 
  1973. File: gawk.info,  Node: GNU Regexp Operators,  Next: Case-sensitivity,  Prev: Regexp Operators,  Up: Regexp
  1974.  
  1975. Additional Regexp Operators Only in `gawk'
  1976. ==========================================
  1977.  
  1978.    GNU software that deals with regular expressions provides a number of
  1979. additional regexp operators.  These operators are described in this
  1980. section, and are specific to `gawk'; they are not available in other
  1981. `awk' implementations.
  1982.  
  1983.    Most of the additional operators are for dealing with word matching.
  1984. For our purposes, a "word" is a sequence of one or more letters, digits,
  1985. or underscores (`_').
  1986.  
  1987. `\w'
  1988.      This operator matches any word-constituent character, i.e. any
  1989.      letter, digit, or underscore. Think of it as a short-hand for
  1990.      `[[:alnum:]_]'.
  1991.  
  1992. `\W'
  1993.      This operator matches any character that is not word-constituent.
  1994.      Think of it as a short-hand for `[^[:alnum:]_]'.
  1995.  
  1996. `\<'
  1997.      This operator matches the empty string at the beginning of a word.
  1998.      For example, `/\<away/' matches `away', but not `stowaway'.
  1999.  
  2000. `\>'
  2001.      This operator matches the empty string at the end of a word.  For
  2002.      example, `/stow\>/' matches `stow', but not `stowaway'.
  2003.  
  2004. `\y'
  2005.      This operator matches the empty string at either the beginning or
  2006.      the end of a word (the word boundar*y*).  For example, `\yballs?\y'
  2007.      matches either `ball' or `balls' as a separate word.
  2008.  
  2009. `\B'
  2010.      This operator matches the empty string within a word. In other
  2011.      words, `\B' matches the empty string that occurs between two
  2012.      word-constituent characters. For example, `/\Brat\B/' matches
  2013.      `crate', but it does not match `dirty rat'.  `\B' is essentially
  2014.      the opposite of `\y'.
  2015.  
  2016.    There are two other operators that work on buffers.  In Emacs, a
  2017. "buffer" is, naturally, an Emacs buffer.  For other programs, the
  2018. regexp library routines that `gawk' uses consider the entire string to
  2019. be matched as the buffer.
  2020.  
  2021.    For `awk', since `^' and `$' always work in terms of the beginning
  2022. and end of strings, these operators don't add any new capabilities.
  2023. They are provided for compatibility with other GNU software.
  2024.  
  2025. `\`'
  2026.      This operator matches the empty string at the beginning of the
  2027.      buffer.
  2028.  
  2029. `\''
  2030.      This operator matches the empty string at the end of the buffer.
  2031.  
  2032.    In other GNU software, the word boundary operator is `\b'. However,
  2033. that conflicts with the `awk' language's definition of `\b' as
  2034. backspace, so `gawk' uses a different letter.
  2035.  
  2036.    An alternative method would have been to require two backslashes in
  2037. the GNU operators, but this was deemed to be too confusing, and the
  2038. current method of using `\y' for the GNU `\b' appears to be the lesser
  2039. of two evils.
  2040.  
  2041.    The various command line options (*note Command Line Options:
  2042. Options.) control how `gawk' interprets characters in regexps.
  2043.  
  2044. No options
  2045.      In the default case, `gawk' provide all the facilities of POSIX
  2046.      regexps and the GNU regexp operators described in *Note Regular
  2047.      Expression Operators: Regexp Operators.  However, interval
  2048.      expressions are not supported.
  2049.  
  2050. `--posix'
  2051.      Only POSIX regexps are supported, the GNU operators are not special
  2052.      (e.g., `\w' matches a literal `w').  Interval expressions are
  2053.      allowed.
  2054.  
  2055. `--traditional'
  2056.      Traditional Unix `awk' regexps are matched. The GNU operators are
  2057.      not special, interval expressions are not available, and neither
  2058.      are the POSIX character classes (`[[:alnum:]]' and so on).
  2059.      Characters described by octal and hexadecimal escape sequences are
  2060.      treated literally, even if they represent regexp metacharacters.
  2061.  
  2062. `--re-interval'
  2063.      Allow interval expressions in regexps, even if `--traditional' has
  2064.      been provided.
  2065.  
  2066. 
  2067. File: gawk.info,  Node: Case-sensitivity,  Next: Leftmost Longest,  Prev: GNU Regexp Operators,  Up: Regexp
  2068.  
  2069. Case-sensitivity in Matching
  2070. ============================
  2071.  
  2072.    Case is normally significant in regular expressions, both when
  2073. matching ordinary characters (i.e. not metacharacters), and inside
  2074. character sets.  Thus a `w' in a regular expression matches only a
  2075. lower-case `w' and not an upper-case `W'.
  2076.  
  2077.    The simplest way to do a case-independent match is to use a character
  2078. list: `[Ww]'.  However, this can be cumbersome if you need to use it
  2079. often; and it can make the regular expressions harder to read.  There
  2080. are two alternatives that you might prefer.
  2081.  
  2082.    One way to do a case-insensitive match at a particular point in the
  2083. program is to convert the data to a single case, using the `tolower' or
  2084. `toupper' built-in string functions (which we haven't discussed yet;
  2085. *note Built-in Functions for String Manipulation: String Functions.).
  2086. For example:
  2087.  
  2088.      tolower($1) ~ /foo/  { ... }
  2089.  
  2090. converts the first field to lower-case before matching against it.
  2091. This will work in any POSIX-compliant implementation of `awk'.
  2092.  
  2093.    Another method, specific to `gawk', is to set the variable
  2094. `IGNORECASE' to a non-zero value (*note Built-in Variables::.).  When
  2095. `IGNORECASE' is not zero, *all* regexp and string operations ignore
  2096. case.  Changing the value of `IGNORECASE' dynamically controls the case
  2097. sensitivity of your program as it runs.  Case is significant by default
  2098. because `IGNORECASE' (like most variables) is initialized to zero.
  2099.  
  2100.      x = "aB"
  2101.      if (x ~ /ab/) ...   # this test will fail
  2102.      
  2103.      IGNORECASE = 1
  2104.      if (x ~ /ab/) ...   # now it will succeed
  2105.  
  2106.    In general, you cannot use `IGNORECASE' to make certain rules
  2107. case-insensitive and other rules case-sensitive, because there is no way
  2108. to set `IGNORECASE' just for the pattern of a particular rule.  To do
  2109. this, you must use character lists or `tolower'.  However, one thing
  2110. you can do only with `IGNORECASE' is turn case-sensitivity on or off
  2111. dynamically for all the rules at once.
  2112.  
  2113.    `IGNORECASE' can be set on the command line, or in a `BEGIN' rule
  2114. (*note Other Command Line Arguments: Other Arguments.; also *note
  2115. Startup and Cleanup Actions: Using BEGIN/END.).  Setting `IGNORECASE'
  2116. from the command line is a way to make a program case-insensitive
  2117. without having to edit it.
  2118.  
  2119.    Prior to version 3.0 of `gawk', the value of `IGNORECASE' only
  2120. affected regexp operations. It did not affect string comparison with
  2121. `==', `!=', and so on.  Beginning with version 3.0, both regexp and
  2122. string comparison operations are affected by `IGNORECASE'.
  2123.  
  2124.    Beginning with version 3.0 of `gawk', the equivalences between
  2125. upper-case and lower-case characters are based on the ISO-8859-1 (ISO
  2126. Latin-1) character set. This character set is a superset of the
  2127. traditional 128 ASCII characters, that also provides a number of
  2128. characters suitable for use with European languages.
  2129.  
  2130.    The value of `IGNORECASE' has no effect if `gawk' is in
  2131. compatibility mode (*note Command Line Options: Options.).  Case is
  2132. always significant in compatibility mode.
  2133.  
  2134. 
  2135. File: gawk.info,  Node: Leftmost Longest,  Next: Computed Regexps,  Prev: Case-sensitivity,  Up: Regexp
  2136.  
  2137. How Much Text Matches?
  2138. ======================
  2139.  
  2140.    Consider the following example:
  2141.  
  2142.      echo aaaabcd | awk '{ sub(/a+/, "<A>"); print }'
  2143.  
  2144.    This example uses the `sub' function (which we haven't discussed yet,
  2145. *note Built-in Functions for String Manipulation: String Functions.) to
  2146. make a change to the input record. Here, the regexp `/a+/' indicates
  2147. "one or more `a' characters," and the replacement text is `<A>'.
  2148.  
  2149.    The input contains four `a' characters.  What will the output be?
  2150. In other words, how many is "one or more"--will `awk' match two, three,
  2151. or all four `a' characters?
  2152.  
  2153.    The answer is, `awk' (and POSIX) regular expressions always match
  2154. the leftmost, *longest* sequence of input characters that can match.
  2155. Thus, in this example, all four `a' characters are replaced with `<A>'.
  2156.  
  2157.      $ echo aaaabcd | awk '{ sub(/a+/, "<A>"); print }'
  2158.      -| <A>bcd
  2159.  
  2160.    For simple match/no-match tests, this is not so important. But when
  2161. doing regexp-based field and record splitting, and text matching and
  2162. substitutions with the `match', `sub', `gsub', and `gensub' functions,
  2163. it is very important.  *Note Built-in Functions for String
  2164. Manipulation: String Functions, for more information on these functions.
  2165. Understanding this principle is also important for regexp-based record
  2166. and field splitting (*note How Input is Split into Records: Records.,
  2167. and also *note Specifying How Fields are Separated: Field Separators.).
  2168.  
  2169. 
  2170. File: gawk.info,  Node: Computed Regexps,  Prev: Leftmost Longest,  Up: Regexp
  2171.  
  2172. Using Dynamic Regexps
  2173. =====================
  2174.  
  2175.    The right hand side of a `~' or `!~' operator need not be a regexp
  2176. constant (i.e. a string of characters between slashes).  It may be any
  2177. expression.  The expression is evaluated, and converted if necessary to
  2178. a string; the contents of the string are used as the regexp.  A regexp
  2179. that is computed in this way is called a "dynamic regexp".  For example:
  2180.  
  2181.      BEGIN { identifier_regexp = "[A-Za-z_][A-Za-z_0-9]+" }
  2182.      $0 ~ identifier_regexp    { print }
  2183.  
  2184. sets `identifier_regexp' to a regexp that describes `awk' variable
  2185. names, and tests if the input record matches this regexp.
  2186.  
  2187.    *Caution:* When using the `~' and `!~' operators, there is a
  2188. difference between a regexp constant enclosed in slashes, and a string
  2189. constant enclosed in double quotes.  If you are going to use a string
  2190. constant, you have to understand that the string is in essence scanned
  2191. *twice*; the first time when `awk' reads your program, and the second
  2192. time when it goes to match the string on the left-hand side of the
  2193. operator with the pattern on the right.  This is true of any string
  2194. valued expression (such as `identifier_regexp' above), not just string
  2195. constants.
  2196.  
  2197.    What difference does it make if the string is scanned twice? The
  2198. answer has to do with escape sequences, and particularly with
  2199. backslashes.  To get a backslash into a regular expression inside a
  2200. string, you have to type two backslashes.
  2201.  
  2202.    For example, `/\*/' is a regexp constant for a literal `*'.  Only
  2203. one backslash is needed.  To do the same thing with a string, you would
  2204. have to type `"\\*"'.  The first backslash escapes the second one, so
  2205. that the string actually contains the two characters `\' and `*'.
  2206.  
  2207.    Given that you can use both regexp and string constants to describe
  2208. regular expressions, which should you use?  The answer is "regexp
  2209. constants," for several reasons.
  2210.  
  2211.   1. String constants are more complicated to write, and more difficult
  2212.      to read. Using regexp constants makes your programs less
  2213.      error-prone.  Not understanding the difference between the two
  2214.      kinds of constants is a common source of errors.
  2215.  
  2216.   2. It is also more efficient to use regexp constants: `awk' can note
  2217.      that you have supplied a regexp and store it internally in a form
  2218.      that makes pattern matching more efficient.  When using a string
  2219.      constant, `awk' must first convert the string into this internal
  2220.      form, and then perform the pattern matching.
  2221.  
  2222.   3. Using regexp constants is better style; it shows clearly that you
  2223.      intend a regexp match.
  2224.  
  2225. 
  2226. File: gawk.info,  Node: Reading Files,  Next: Printing,  Prev: Regexp,  Up: Top
  2227.  
  2228. Reading Input Files
  2229. *******************
  2230.  
  2231.    In the typical `awk' program, all input is read either from the
  2232. standard input (by default the keyboard, but often a pipe from another
  2233. command) or from files whose names you specify on the `awk' command
  2234. line.  If you specify input files, `awk' reads them in order, reading
  2235. all the data from one before going on to the next.  The name of the
  2236. current input file can be found in the built-in variable `FILENAME'
  2237. (*note Built-in Variables::.).
  2238.  
  2239.    The input is read in units called "records", and processed by the
  2240. rules of your program one record at a time.  By default, each record is
  2241. one line.  Each record is automatically split into chunks called
  2242. "fields".  This makes it more convenient for programs to work on the
  2243. parts of a record.
  2244.  
  2245.    On rare occasions you will need to use the `getline' command.  The
  2246. `getline' command is valuable, both because it can do explicit input
  2247. from any number of files, and because the files used with it do not
  2248. have to be named on the `awk' command line (*note Explicit Input with
  2249. `getline': Getline.).
  2250.  
  2251. * Menu:
  2252.  
  2253. * Records::                     Controlling how data is split into records.
  2254. * Fields::                      An introduction to fields.
  2255. * Non-Constant Fields::         Non-constant Field Numbers.
  2256. * Changing Fields::             Changing the Contents of a Field.
  2257. * Field Separators::            The field separator and how to change it.
  2258. * Constant Size::               Reading constant width data.
  2259. * Multiple Line::               Reading multi-line records.
  2260. * Getline::                     Reading files under explicit program control
  2261.                                 using the `getline' function.
  2262.  
  2263. 
  2264. File: gawk.info,  Node: Records,  Next: Fields,  Prev: Reading Files,  Up: Reading Files
  2265.  
  2266. How Input is Split into Records
  2267. ===============================
  2268.  
  2269.    The `awk' utility divides the input for your `awk' program into
  2270. records and fields.  Records are separated by a character called the
  2271. "record separator".  By default, the record separator is the newline
  2272. character.  This is why records are, by default, single lines.  You can
  2273. use a different character for the record separator by assigning the
  2274. character to the built-in variable `RS'.
  2275.  
  2276.    You can change the value of `RS' in the `awk' program, like any
  2277. other variable, with the assignment operator, `=' (*note Assignment
  2278. Expressions: Assignment Ops.).  The new record-separator character
  2279. should be enclosed in quotation marks, which indicate a string
  2280. constant.  Often the right time to do this is at the beginning of
  2281. execution, before any input has been processed, so that the very first
  2282. record will be read with the proper separator.  To do this, use the
  2283. special `BEGIN' pattern (*note The `BEGIN' and `END' Special Patterns:
  2284. BEGIN/END.).  For example:
  2285.  
  2286.      awk 'BEGIN { RS = "/" } ; { print $0 }' BBS-list
  2287.  
  2288. changes the value of `RS' to `"/"', before reading any input.  This is
  2289. a string whose first character is a slash; as a result, records are
  2290. separated by slashes.  Then the input file is read, and the second rule
  2291. in the `awk' program (the action with no pattern) prints each record.
  2292. Since each `print' statement adds a newline at the end of its output,
  2293. the effect of this `awk' program is to copy the input with each slash
  2294. changed to a newline.  Here are the results of running the program on
  2295. `BBS-list':
  2296.  
  2297.      $ awk 'BEGIN { RS = "/" } ; { print $0 }' BBS-list
  2298.      -| aardvark     555-5553     1200
  2299.      -| 300          B
  2300.      -| alpo-net     555-3412     2400
  2301.      -| 1200
  2302.      -| 300     A
  2303.      -| barfly       555-7685     1200
  2304.      -| 300          A
  2305.      -| bites        555-1675     2400
  2306.      -| 1200
  2307.      -| 300     A
  2308.      -| camelot      555-0542     300               C
  2309.      -| core         555-2912     1200
  2310.      -| 300          C
  2311.      -| fooey        555-1234     2400
  2312.      -| 1200
  2313.      -| 300     B
  2314.      -| foot         555-6699     1200
  2315.      -| 300          B
  2316.      -| macfoo       555-6480     1200
  2317.      -| 300          A
  2318.      -| sdace        555-3430     2400
  2319.      -| 1200
  2320.      -| 300     A
  2321.      -| sabafoo      555-2127     1200
  2322.      -| 300          C
  2323.      -|
  2324.  
  2325. Note that the entry for the `camelot' BBS is not split.  In the
  2326. original data file (*note Data Files for the Examples: Sample Data
  2327. Files.), the line looks like this:
  2328.  
  2329.      camelot      555-0542     300               C
  2330.  
  2331. It only has one baud rate; there are no slashes in the record.
  2332.  
  2333.    Another way to change the record separator is on the command line,
  2334. using the variable-assignment feature (*note Other Command Line
  2335. Arguments: Other Arguments.).
  2336.  
  2337.      awk '{ print $0 }' RS="/" BBS-list
  2338.  
  2339. This sets `RS' to `/' before processing `BBS-list'.
  2340.  
  2341.    Using an unusual character such as `/' for the record separator
  2342. produces correct behavior in the vast majority of cases.  However, the
  2343. following (extreme) pipeline prints a surprising `1'.  There is one
  2344. field, consisting of a newline.  The value of the built-in variable
  2345. `NF' is the number of fields in the current record.
  2346.  
  2347.      $ echo | awk 'BEGIN { RS = "a" } ; { print NF }'
  2348.      -| 1
  2349.  
  2350. Reaching the end of an input file terminates the current input record,
  2351. even if the last character in the file is not the character in `RS'
  2352. (d.c.).
  2353.  
  2354.    The empty string, `""' (a string of no characters), has a special
  2355. meaning as the value of `RS': it means that records are separated by
  2356. one or more blank lines, and nothing else.  *Note Multiple-Line
  2357. Records: Multiple Line, for more details.
  2358.  
  2359.    If you change the value of `RS' in the middle of an `awk' run, the
  2360. new value is used to delimit subsequent records, but the record
  2361. currently being processed (and records already processed) are not
  2362. affected.
  2363.  
  2364.    After the end of the record has been determined, `gawk' sets the
  2365. variable `RT' to the text in the input that matched `RS'.
  2366.  
  2367.    The value of `RS' is in fact not limited to a one-character string.
  2368. It can be any regular expression (*note Regular Expressions: Regexp.).
  2369. In general, each record ends at the next string that matches the
  2370. regular expression; the next record starts at the end of the matching
  2371. string.  This general rule is actually at work in the usual case, where
  2372. `RS' contains just a newline: a record ends at the beginning of the
  2373. next matching string (the next newline in the input) and the following
  2374. record starts just after the end of this string (at the first character
  2375. of the following line).  The newline, since it matches `RS', is not
  2376. part of either record.
  2377.  
  2378.    When `RS' is a single character, `RT' will contain the same single
  2379. character. However, when `RS' is a regular expression, then `RT'
  2380. becomes more useful; it contains the actual input text that matched the
  2381. regular expression.
  2382.  
  2383.    The following example illustrates both of these features.  It sets
  2384. `RS' equal to a regular expression that matches either a newline, or a
  2385. series of one or more upper-case letters with optional leading and/or
  2386. trailing white space (*note Regular Expressions: Regexp.).
  2387.  
  2388.      $ echo record 1 AAAA record 2 BBBB record 3 |
  2389.      > gawk 'BEGIN { RS = "\n|( *[[:upper:]]+ *)" }
  2390.      >             { print "Record =", $0, "and RT =", RT }'
  2391.      -| Record = record 1 and RT =  AAAA
  2392.      -| Record = record 2 and RT =  BBBB
  2393.      -| Record = record 3 and RT =
  2394.      -|
  2395.  
  2396. The final line of output has an extra blank line. This is because the
  2397. value of `RT' is a newline, and then the `print' statement supplies its
  2398. own terminating newline.
  2399.  
  2400.    *Note A Simple Stream Editor: Simple Sed, for a more useful example
  2401. of `RS' as a regexp and `RT'.
  2402.  
  2403.    The use of `RS' as a regular expression and the `RT' variable are
  2404. `gawk' extensions; they are not available in compatibility mode (*note
  2405. Command Line Options: Options.).  In compatibility mode, only the first
  2406. character of the value of `RS' is used to determine the end of the
  2407. record.
  2408.  
  2409.    The `awk' utility keeps track of the number of records that have
  2410. been read so far from the current input file.  This value is stored in a
  2411. built-in variable called `FNR'.  It is reset to zero when a new file is
  2412. started.  Another built-in variable, `NR', is the total number of input
  2413. records read so far from all data files.  It starts at zero but is
  2414. never automatically reset to zero.
  2415.  
  2416. 
  2417. File: gawk.info,  Node: Fields,  Next: Non-Constant Fields,  Prev: Records,  Up: Reading Files
  2418.  
  2419. Examining Fields
  2420. ================
  2421.  
  2422.    When `awk' reads an input record, the record is automatically
  2423. separated or "parsed" by the interpreter into chunks called "fields".
  2424. By default, fields are separated by whitespace, like words in a line.
  2425. Whitespace in `awk' means any string of one or more spaces and/or tabs;
  2426. other characters such as newline, formfeed, and so on, that are
  2427. considered whitespace by other languages are *not* considered
  2428. whitespace by `awk'.
  2429.  
  2430.    The purpose of fields is to make it more convenient for you to refer
  2431. to these pieces of the record.  You don't have to use them--you can
  2432. operate on the whole record if you wish--but fields are what make
  2433. simple `awk' programs so powerful.
  2434.  
  2435.    To refer to a field in an `awk' program, you use a dollar-sign, `$',
  2436. followed by the number of the field you want.  Thus, `$1' refers to the
  2437. first field, `$2' to the second, and so on.  For example, suppose the
  2438. following is a line of input:
  2439.  
  2440.      This seems like a pretty nice example.
  2441.  
  2442. Here the first field, or `$1', is `This'; the second field, or `$2', is
  2443. `seems'; and so on.  Note that the last field, `$7', is `example.'.
  2444. Because there is no space between the `e' and the `.', the period is
  2445. considered part of the seventh field.
  2446.  
  2447.    `NF' is a built-in variable whose value is the number of fields in
  2448. the current record.  `awk' updates the value of `NF' automatically,
  2449. each time a record is read.
  2450.  
  2451.    No matter how many fields there are, the last field in a record can
  2452. be represented by `$NF'.  So, in the example above, `$NF' would be the
  2453. same as `$7', which is `example.'.  Why this works is explained below
  2454. (*note Non-constant Field Numbers: Non-Constant Fields.).  If you try
  2455. to reference a field beyond the last one, such as `$8' when the record
  2456. has only seven fields, you get the empty string.
  2457.  
  2458.    `$0', which looks like a reference to the "zeroth" field, is a
  2459. special case: it represents the whole input record.  `$0' is used when
  2460. you are not interested in fields.
  2461.  
  2462.    Here are some more examples:
  2463.  
  2464.      $ awk '$1 ~ /foo/ { print $0 }' BBS-list
  2465.      -| fooey        555-1234     2400/1200/300     B
  2466.      -| foot         555-6699     1200/300          B
  2467.      -| macfoo       555-6480     1200/300          A
  2468.      -| sabafoo      555-2127     1200/300          C
  2469.  
  2470. This example prints each record in the file `BBS-list' whose first
  2471. field contains the string `foo'.  The operator `~' is called a
  2472. "matching operator" (*note How to Use Regular Expressions: Regexp
  2473. Usage.); it tests whether a string (here, the field `$1') matches a
  2474. given regular expression.
  2475.  
  2476.    By contrast, the following example looks for `foo' in *the entire
  2477. record* and prints the first field and the last field for each input
  2478. record containing a match.
  2479.  
  2480.      $ awk '/foo/ { print $1, $NF }' BBS-list
  2481.      -| fooey B
  2482.      -| foot B
  2483.      -| macfoo A
  2484.      -| sabafoo C
  2485.  
  2486. 
  2487. File: gawk.info,  Node: Non-Constant Fields,  Next: Changing Fields,  Prev: Fields,  Up: Reading Files
  2488.  
  2489. Non-constant Field Numbers
  2490. ==========================
  2491.  
  2492.    The number of a field does not need to be a constant.  Any
  2493. expression in the `awk' language can be used after a `$' to refer to a
  2494. field.  The value of the expression specifies the field number.  If the
  2495. value is a string, rather than a number, it is converted to a number.
  2496. Consider this example:
  2497.  
  2498.      awk '{ print $NR }'
  2499.  
  2500. Recall that `NR' is the number of records read so far: one in the first
  2501. record, two in the second, etc.  So this example prints the first field
  2502. of the first record, the second field of the second record, and so on.
  2503. For the twentieth record, field number 20 is printed; most likely, the
  2504. record has fewer than 20 fields, so this prints a blank line.
  2505.  
  2506.    Here is another example of using expressions as field numbers:
  2507.  
  2508.      awk '{ print $(2*2) }' BBS-list
  2509.  
  2510.    `awk' must evaluate the expression `(2*2)' and use its value as the
  2511. number of the field to print.  The `*' sign represents multiplication,
  2512. so the expression `2*2' evaluates to four.  The parentheses are used so
  2513. that the multiplication is done before the `$' operation; they are
  2514. necessary whenever there is a binary operator in the field-number
  2515. expression.  This example, then, prints the hours of operation (the
  2516. fourth field) for every line of the file `BBS-list'.  (All of the `awk'
  2517. operators are listed, in order of decreasing precedence, in *Note
  2518. Operator Precedence (How Operators Nest): Precedence.)
  2519.  
  2520.    If the field number you compute is zero, you get the entire record.
  2521. Thus, `$(2-2)' has the same value as `$0'.  Negative field numbers are
  2522. not allowed; trying to reference one will usually terminate your
  2523. running `awk' program.  (The POSIX standard does not define what
  2524. happens when you reference a negative field number.  `gawk' will notice
  2525. this and terminate your program.  Other `awk' implementations may
  2526. behave differently.)
  2527.  
  2528.    As mentioned in *Note Examining Fields: Fields, the number of fields
  2529. in the current record is stored in the built-in variable `NF' (also
  2530. *note Built-in Variables::.).  The expression `$NF' is not a special
  2531. feature: it is the direct consequence of evaluating `NF' and using its
  2532. value as a field number.
  2533.  
  2534. 
  2535. File: gawk.info,  Node: Changing Fields,  Next: Field Separators,  Prev: Non-Constant Fields,  Up: Reading Files
  2536.  
  2537. Changing the Contents of a Field
  2538. ================================
  2539.  
  2540.    You can change the contents of a field as seen by `awk' within an
  2541. `awk' program; this changes what `awk' perceives as the current input
  2542. record.  (The actual input is untouched; `awk' *never* modifies the
  2543. input file.)
  2544.  
  2545.    Consider this example and its output:
  2546.  
  2547.      $ awk '{ $3 = $2 - 10; print $2, $3 }' inventory-shipped
  2548.      -| 13 3
  2549.      -| 15 5
  2550.      -| 15 5
  2551.      ...
  2552.  
  2553. The `-' sign represents subtraction, so this program reassigns field
  2554. three, `$3', to be the value of field two minus ten, `$2 - 10'.  (*Note
  2555. Arithmetic Operators: Arithmetic Ops.) Then field two, and the new
  2556. value for field three, are printed.
  2557.  
  2558.    In order for this to work, the text in field `$2' must make sense as
  2559. a number; the string of characters must be converted to a number in
  2560. order for the computer to do arithmetic on it.  The number resulting
  2561. from the subtraction is converted back to a string of characters which
  2562. then becomes field three.  *Note Conversion of Strings and Numbers:
  2563. Conversion.
  2564.  
  2565.    When you change the value of a field (as perceived by `awk'), the
  2566. text of the input record is recalculated to contain the new field where
  2567. the old one was.  Therefore, `$0' changes to reflect the altered field.
  2568. Thus, this program prints a copy of the input file, with 10 subtracted
  2569. from the second field of each line.
  2570.  
  2571.      $ awk '{ $2 = $2 - 10; print $0 }' inventory-shipped
  2572.      -| Jan 3 25 15 115
  2573.      -| Feb 5 32 24 226
  2574.      -| Mar 5 24 34 228
  2575.      ...
  2576.  
  2577.    You can also assign contents to fields that are out of range.  For
  2578. example:
  2579.  
  2580.      $ awk '{ $6 = ($5 + $4 + $3 + $2)
  2581.      >        print $6 }' inventory-shipped
  2582.      -| 168
  2583.      -| 297
  2584.      -| 301
  2585.      ...
  2586.  
  2587. We've just created `$6', whose value is the sum of fields `$2', `$3',
  2588. `$4', and `$5'.  The `+' sign represents addition.  For the file
  2589. `inventory-shipped', `$6' represents the total number of parcels
  2590. shipped for a particular month.
  2591.  
  2592.    Creating a new field changes `awk''s internal copy of the current
  2593. input record--the value of `$0'.  Thus, if you do `print $0' after
  2594. adding a field, the record printed includes the new field, with the
  2595. appropriate number of field separators between it and the previously
  2596. existing fields.
  2597.  
  2598.    This recomputation affects and is affected by `NF' (the number of
  2599. fields; *note Examining Fields: Fields.), and by a feature that has not
  2600. been discussed yet, the "output field separator", `OFS', which is used
  2601. to separate the fields (*note Output Separators::.).  For example, the
  2602. value of `NF' is set to the number of the highest field you create.
  2603.  
  2604.    Note, however, that merely *referencing* an out-of-range field does
  2605. *not* change the value of either `$0' or `NF'.  Referencing an
  2606. out-of-range field only produces an empty string.  For example:
  2607.  
  2608.      if ($(NF+1) != "")
  2609.          print "can't happen"
  2610.      else
  2611.          print "everything is normal"
  2612.  
  2613. should print `everything is normal', because `NF+1' is certain to be
  2614. out of range.  (*Note The `if'-`else' Statement: If Statement, for more
  2615. information about `awk''s `if-else' statements.  *Note Variable Typing
  2616. and Comparison Expressions: Typing and Comparison, for more information
  2617. about the `!=' operator.)
  2618.  
  2619.    It is important to note that making an assignment to an existing
  2620. field will change the value of `$0', but will not change the value of
  2621. `NF', even when you assign the empty string to a field.  For example:
  2622.  
  2623.      $ echo a b c d | awk '{ OFS = ":"; $2 = ""
  2624.      >                       print $0; print NF }'
  2625.      -| a::c:d
  2626.      -| 4
  2627.  
  2628. The field is still there; it just has an empty value.  You can tell
  2629. because there are two colons in a row.
  2630.  
  2631.    This example shows what happens if you create a new field.
  2632.  
  2633.      $ echo a b c d | awk '{ OFS = ":"; $2 = ""; $6 = "new"
  2634.      >                       print $0; print NF }'
  2635.      -| a::c:d::new
  2636.      -| 6
  2637.  
  2638. The intervening field, `$5' is created with an empty value (indicated
  2639. by the second pair of adjacent colons), and `NF' is updated with the
  2640. value six.
  2641.  
  2642. 
  2643. File: gawk.info,  Node: Field Separators,  Next: Constant Size,  Prev: Changing Fields,  Up: Reading Files
  2644.  
  2645. Specifying How Fields are Separated
  2646. ===================================
  2647.  
  2648.    This section is rather long; it describes one of the most fundamental
  2649. operations in `awk'.
  2650.  
  2651. * Menu:
  2652.  
  2653. * Basic Field Splitting::        How fields are split with single characters
  2654.                                  or simple strings.
  2655. * Regexp Field Splitting::       Using regexps as the field separator.
  2656. * Single Character Fields::      Making each character a separate field.
  2657. * Command Line Field Separator:: Setting `FS' from the command line.
  2658. * Field Splitting Summary::      Some final points and a summary table.
  2659.  
  2660. 
  2661. File: gawk.info,  Node: Basic Field Splitting,  Next: Regexp Field Splitting,  Prev: Field Separators,  Up: Field Separators
  2662.  
  2663. The Basics of Field Separating
  2664. ------------------------------
  2665.  
  2666.    The "field separator", which is either a single character or a
  2667. regular expression, controls the way `awk' splits an input record into
  2668. fields.  `awk' scans the input record for character sequences that
  2669. match the separator; the fields themselves are the text between the
  2670. matches.
  2671.  
  2672.    In the examples below, we use the bullet symbol "*" to represent
  2673. spaces in the output.
  2674.  
  2675.    If the field separator is `oo', then the following line:
  2676.  
  2677.      moo goo gai pan
  2678.  
  2679. would be split into three fields: `m', `*g' and `*gai*pan'.  Note the
  2680. leading spaces in the values of the second and third fields.
  2681.  
  2682.    The field separator is represented by the built-in variable `FS'.
  2683. Shell programmers take note!  `awk' does *not* use the name `IFS' which
  2684. is used by the POSIX compatible shells (such as the Bourne shell, `sh',
  2685. or the GNU Bourne-Again Shell, Bash).
  2686.  
  2687.    You can change the value of `FS' in the `awk' program with the
  2688. assignment operator, `=' (*note Assignment Expressions: Assignment
  2689. Ops.).  Often the right time to do this is at the beginning of
  2690. execution, before any input has been processed, so that the very first
  2691. record will be read with the proper separator.  To do this, use the
  2692. special `BEGIN' pattern (*note The `BEGIN' and `END' Special Patterns:
  2693. BEGIN/END.).  For example, here we set the value of `FS' to the string
  2694. `","':
  2695.  
  2696.      awk 'BEGIN { FS = "," } ; { print $2 }'
  2697.  
  2698. Given the input line,
  2699.  
  2700.      John Q. Smith, 29 Oak St., Walamazoo, MI 42139
  2701.  
  2702. this `awk' program extracts and prints the string `*29*Oak*St.'.
  2703.  
  2704.    Sometimes your input data will contain separator characters that
  2705. don't separate fields the way you thought they would.  For instance, the
  2706. person's name in the example we just used might have a title or suffix
  2707. attached, such as `John Q. Smith, LXIX'.  From input containing such a
  2708. name:
  2709.  
  2710.      John Q. Smith, LXIX, 29 Oak St., Walamazoo, MI 42139
  2711.  
  2712. the above program would extract `*LXIX', instead of `*29*Oak*St.'.  If
  2713. you were expecting the program to print the address, you would be
  2714. surprised.  The moral is: choose your data layout and separator
  2715. characters carefully to prevent such problems.
  2716.  
  2717.    Normally, fields are separated by whitespace sequences (spaces and
  2718. tabs), not by single spaces: two spaces in a row do not delimit an
  2719. empty field.  The default value of the field separator `FS' is a string
  2720. containing a single space, `" "'.  If this value were interpreted in
  2721. the usual way, each space character would separate fields, so two
  2722. spaces in a row would make an empty field between them.  The reason
  2723. this does not happen is that a single space as the value of `FS' is a
  2724. special case: it is taken to specify the default manner of delimiting
  2725. fields.
  2726.  
  2727.    If `FS' is any other single character, such as `","', then each
  2728. occurrence of that character separates two fields.  Two consecutive
  2729. occurrences delimit an empty field.  If the character occurs at the
  2730. beginning or the end of the line, that too delimits an empty field.  The
  2731. space character is the only single character which does not follow these
  2732. rules.
  2733.  
  2734. 
  2735. File: gawk.info,  Node: Regexp Field Splitting,  Next: Single Character Fields,  Prev: Basic Field Splitting,  Up: Field Separators
  2736.  
  2737. Using Regular Expressions to Separate Fields
  2738. --------------------------------------------
  2739.  
  2740.    The previous node discussed the use of single characters or simple
  2741. strings as the value of `FS'.  More generally, the value of `FS' may be
  2742. a string containing any regular expression.  In this case, each match
  2743. in the record for the regular expression separates fields.  For
  2744. example, the assignment:
  2745.  
  2746.      FS = ", \t"
  2747.  
  2748. makes every area of an input line that consists of a comma followed by a
  2749. space and a tab, into a field separator.  (`\t' is an "escape sequence"
  2750. that stands for a tab; *note Escape Sequences::., for the complete list
  2751. of similar escape sequences.)
  2752.  
  2753.    For a less trivial example of a regular expression, suppose you want
  2754. single spaces to separate fields the way single commas were used above.
  2755. You can set `FS' to `"[ ]"' (left bracket, space, right bracket).  This
  2756. regular expression matches a single space and nothing else (*note
  2757. Regular Expressions: Regexp.).
  2758.  
  2759.    There is an important difference between the two cases of `FS = " "'
  2760. (a single space) and `FS = "[ \t]+"' (left bracket, space, backslash,
  2761. "t", right bracket, which is a regular expression matching one or more
  2762. spaces or tabs).  For both values of `FS', fields are separated by runs
  2763. of spaces and/or tabs.  However, when the value of `FS' is `" "', `awk'
  2764. will first strip leading and trailing whitespace from the record, and
  2765. then decide where the fields are.
  2766.  
  2767.    For example, the following pipeline prints `b':
  2768.  
  2769.      $ echo ' a b c d ' | awk '{ print $2 }'
  2770.      -| b
  2771.  
  2772. However, this pipeline prints `a' (note the extra spaces around each
  2773. letter):
  2774.  
  2775.      $ echo ' a  b  c  d ' | awk 'BEGIN { FS = "[ \t]+" }
  2776.      >                                  { print $2 }'
  2777.      -| a
  2778.  
  2779. In this case, the first field is "null", or empty.
  2780.  
  2781.    The stripping of leading and trailing whitespace also comes into
  2782. play whenever `$0' is recomputed.  For instance, study this pipeline:
  2783.  
  2784.      $ echo '   a b c d' | awk '{ print; $2 = $2; print }'
  2785.      -|    a b c d
  2786.      -| a b c d
  2787.  
  2788. The first `print' statement prints the record as it was read, with
  2789. leading whitespace intact.  The assignment to `$2' rebuilds `$0' by
  2790. concatenating `$1' through `$NF' together, separated by the value of
  2791. `OFS'.  Since the leading whitespace was ignored when finding `$1', it
  2792. is not part of the new `$0'.  Finally, the last `print' statement
  2793. prints the new `$0'.
  2794.  
  2795. 
  2796. File: gawk.info,  Node: Single Character Fields,  Next: Command Line Field Separator,  Prev: Regexp Field Splitting,  Up: Field Separators
  2797.  
  2798. Making Each Character a Separate Field
  2799. --------------------------------------
  2800.  
  2801.    There are times when you may want to examine each character of a
  2802. record separately.  In `gawk', this is easy to do, you simply assign
  2803. the null string (`""') to `FS'. In this case, each individual character
  2804. in the record will become a separate field.  Here is an example:
  2805.  
  2806.      echo a b | gawk 'BEGIN { FS = "" }
  2807.                       {
  2808.                           for (i = 1; i <= NF; i = i + 1)
  2809.                               print "Field", i, "is", $i
  2810.                       }'
  2811.  
  2812. The output from this is:
  2813.  
  2814.      Field 1 is a
  2815.      Field 2 is
  2816.      Field 3 is b
  2817.  
  2818.    Traditionally, the behavior for `FS' equal to `""' was not defined.
  2819. In this case, Unix `awk' would simply treat the entire record as only
  2820. having one field (d.c.).  In compatibility mode (*note Command Line
  2821. Options: Options.), if `FS' is the null string, then `gawk' will also
  2822. behave this way.
  2823.  
  2824. 
  2825. File: gawk.info,  Node: Command Line Field Separator,  Next: Field Splitting Summary,  Prev: Single Character Fields,  Up: Field Separators
  2826.  
  2827. Setting `FS' from the Command Line
  2828. ----------------------------------
  2829.  
  2830.    `FS' can be set on the command line.  You use the `-F' option to do
  2831. so.  For example:
  2832.  
  2833.      awk -F, 'PROGRAM' INPUT-FILES
  2834.  
  2835. sets `FS' to be the `,' character.  Notice that the option uses a
  2836. capital `F'.  Contrast this with `-f', which specifies a file
  2837. containing an `awk' program.  Case is significant in command line
  2838. options: the `-F' and `-f' options have nothing to do with each other.
  2839. You can use both options at the same time to set the `FS' variable
  2840. *and* get an `awk' program from a file.
  2841.  
  2842.    The value used for the argument to `-F' is processed in exactly the
  2843. same way as assignments to the built-in variable `FS'.  This means that
  2844. if the field separator contains special characters, they must be escaped
  2845. appropriately.  For example, to use a `\' as the field separator, you
  2846. would have to type:
  2847.  
  2848.      # same as FS = "\\"
  2849.      awk -F\\\\ '...' files ...
  2850.  
  2851. Since `\' is used for quoting in the shell, `awk' will see `-F\\'.
  2852. Then `awk' processes the `\\' for escape characters (*note Escape
  2853. Sequences::.), finally yielding a single `\' to be used for the field
  2854. separator.
  2855.  
  2856.    As a special case, in compatibility mode (*note Command Line
  2857. Options: Options.), if the argument to `-F' is `t', then `FS' is set to
  2858. the tab character.  This is because if you type `-F\t' at the shell,
  2859. without any quotes, the `\' gets deleted, so `awk' figures that you
  2860. really want your fields to be separated with tabs, and not `t's.  Use
  2861. `-v FS="t"' on the command line if you really do want to separate your
  2862. fields with `t's (*note Command Line Options: Options.).
  2863.  
  2864.    For example, let's use an `awk' program file called `baud.awk' that
  2865. contains the pattern `/300/', and the action `print $1'.  Here is the
  2866. program:
  2867.  
  2868.      /300/   { print $1 }
  2869.  
  2870.    Let's also set `FS' to be the `-' character, and run the program on
  2871. the file `BBS-list'.  The following command prints a list of the names
  2872. of the bulletin boards that operate at 300 baud and the first three
  2873. digits of their phone numbers:
  2874.  
  2875.      $ awk -F- -f baud.awk BBS-list
  2876.      -| aardvark     555
  2877.      -| alpo
  2878.      -| barfly       555
  2879.      ...
  2880.  
  2881. Note the second line of output.  In the original file (*note Data Files
  2882. for the Examples: Sample Data Files.), the second line looked like this:
  2883.  
  2884.      alpo-net     555-3412     2400/1200/300     A
  2885.  
  2886.    The `-' as part of the system's name was used as the field
  2887. separator, instead of the `-' in the phone number that was originally
  2888. intended.  This demonstrates why you have to be careful in choosing
  2889. your field and record separators.
  2890.  
  2891.    On many Unix systems, each user has a separate entry in the system
  2892. password file, one line per user.  The information in these lines is
  2893. separated by colons.  The first field is the user's logon name, and the
  2894. second is the user's encrypted password.  A password file entry might
  2895. look like this:
  2896.  
  2897.      arnold:xyzzy:2076:10:Arnold Robbins:/home/arnold:/bin/sh
  2898.  
  2899.    The following program searches the system password file, and prints
  2900. the entries for users who have no password:
  2901.  
  2902.      awk -F: '$2 == ""' /etc/passwd
  2903.  
  2904. 
  2905. File: gawk.info,  Node: Field Splitting Summary,  Prev: Command Line Field Separator,  Up: Field Separators
  2906.  
  2907. Field Splitting Summary
  2908. -----------------------
  2909.  
  2910.    According to the POSIX standard, `awk' is supposed to behave as if
  2911. each record is split into fields at the time that it is read.  In
  2912. particular, this means that you can change the value of `FS' after a
  2913. record is read, and the value of the fields (i.e. how they were split)
  2914. should reflect the old value of `FS', not the new one.
  2915.  
  2916.    However, many implementations of `awk' do not work this way.
  2917. Instead, they defer splitting the fields until a field is actually
  2918. referenced.  The fields will be split using the *current* value of
  2919. `FS'! (d.c.) This behavior can be difficult to diagnose. The following
  2920. example illustrates the difference between the two methods.  (The
  2921. `sed'(1) command prints just the first line of `/etc/passwd'.)
  2922.  
  2923.      sed 1q /etc/passwd | awk '{ FS = ":" ; print $1 }'
  2924.  
  2925. will usually print
  2926.  
  2927.      root
  2928.  
  2929. on an incorrect implementation of `awk', while `gawk' will print
  2930. something like
  2931.  
  2932.      root:nSijPlPhZZwgE:0:0:Root:/:
  2933.  
  2934.    The following table summarizes how fields are split, based on the
  2935. value of `FS'. (`==' means "is equal to.")
  2936.  
  2937. `FS == " "'
  2938.      Fields are separated by runs of whitespace.  Leading and trailing
  2939.      whitespace are ignored.  This is the default.
  2940.  
  2941. `FS == ANY OTHER SINGLE CHARACTER'
  2942.      Fields are separated by each occurrence of the character.  Multiple
  2943.      successive occurrences delimit empty fields, as do leading and
  2944.      trailing occurrences.  The character can even be a regexp
  2945.      metacharacter; it does not need to be escaped.
  2946.  
  2947. `FS == REGEXP'
  2948.      Fields are separated by occurrences of characters that match
  2949.      REGEXP.  Leading and trailing matches of REGEXP delimit empty
  2950.      fields.
  2951.  
  2952. `FS == ""'
  2953.      Each individual character in the record becomes a separate field.
  2954.  
  2955.    ---------- Footnotes ----------
  2956.  
  2957.    (1)  The `sed' utility is a "stream editor." Its behavior is also
  2958. defined by the POSIX standard.
  2959.  
  2960. 
  2961. File: gawk.info,  Node: Constant Size,  Next: Multiple Line,  Prev: Field Separators,  Up: Reading Files
  2962.  
  2963. Reading Fixed-width Data
  2964. ========================
  2965.  
  2966.    (This section discusses an advanced, experimental feature.  If you
  2967. are a novice `awk' user, you may wish to skip it on the first reading.)
  2968.  
  2969.    `gawk' version 2.13 introduced a new facility for dealing with
  2970. fixed-width fields with no distinctive field separator.  Data of this
  2971. nature arises, for example, in  the input for old FORTRAN programs where
  2972. numbers are run together; or in the output of programs that did not
  2973. anticipate the use of their output as input for other programs.
  2974.  
  2975.    An example of the latter is a table where all the columns are lined
  2976. up by the use of a variable number of spaces and *empty fields are just
  2977. spaces*.  Clearly, `awk''s normal field splitting based on `FS' will
  2978. not work well in this case.  Although a portable `awk' program can use
  2979. a series of `substr' calls on `$0' (*note Built-in Functions for String
  2980. Manipulation: String Functions.), this is awkward and inefficient for a
  2981. large number of fields.
  2982.  
  2983.    The splitting of an input record into fixed-width fields is
  2984. specified by assigning a string containing space-separated numbers to
  2985. the built-in variable `FIELDWIDTHS'.  Each number specifies the width
  2986. of the field *including* columns between fields.  If you want to ignore
  2987. the columns between fields, you can specify the width as a separate
  2988. field that is subsequently ignored.
  2989.  
  2990.    The following data is the output of the Unix `w' utility.  It is
  2991. useful to illustrate the use of `FIELDWIDTHS'.
  2992.  
  2993.       10:06pm  up 21 days, 14:04,  23 users
  2994.      User     tty       login  idle   JCPU   PCPU  what
  2995.      hzuo     ttyV0     8:58pm            9      5  vi p24.tex
  2996.      hzang    ttyV3     6:37pm    50                -csh
  2997.      eklye    ttyV5     9:53pm            7      1  em thes.tex
  2998.      dportein ttyV6     8:17pm  1:47                -csh
  2999.      gierd    ttyD3    10:00pm     1                elm
  3000.      dave     ttyD4     9:47pm            4      4  w
  3001.      brent    ttyp0    26Jun91  4:46  26:46   4:41  bash
  3002.      dave     ttyq4    26Jun9115days     46     46  wnewmail
  3003.  
  3004.    The following program takes the above input, converts the idle time
  3005. to number of seconds and prints out the first two fields and the
  3006. calculated idle time.  (This program uses a number of `awk' features
  3007. that haven't been introduced yet.)
  3008.  
  3009.      BEGIN  { FIELDWIDTHS = "9 6 10 6 7 7 35" }
  3010.      NR > 2 {
  3011.          idle = $4
  3012.          sub(/^  */, "", idle)   # strip leading spaces
  3013.          if (idle == "")
  3014.              idle = 0
  3015.          if (idle ~ /:/) {
  3016.              split(idle, t, ":")
  3017.              idle = t[1] * 60 + t[2]
  3018.          }
  3019.          if (idle ~ /days/)
  3020.              idle *= 24 * 60 * 60
  3021.      
  3022.          print $1, $2, idle
  3023.      }
  3024.  
  3025.    Here is the result of running the program on the data:
  3026.  
  3027.      hzuo      ttyV0  0
  3028.      hzang     ttyV3  50
  3029.      eklye     ttyV5  0
  3030.      dportein  ttyV6  107
  3031.      gierd     ttyD3  1
  3032.      dave      ttyD4  0
  3033.      brent     ttyp0  286
  3034.      dave      ttyq4  1296000
  3035.  
  3036.    Another (possibly more practical) example of fixed-width input data
  3037. would be the input from a deck of balloting cards.  In some parts of
  3038. the United States, voters mark their choices by punching holes in
  3039. computer cards.  These cards are then processed to count the votes for
  3040. any particular candidate or on any particular issue.  Since a voter may
  3041. choose not to vote on some issue, any column on the card may be empty.
  3042. An `awk' program for processing such data could use the `FIELDWIDTHS'
  3043. feature to simplify reading the data.  (Of course, getting `gawk' to
  3044. run on a system with card readers is another story!)
  3045.  
  3046.    Assigning a value to `FS' causes `gawk' to return to using `FS' for
  3047. field splitting.  Use `FS = FS' to make this happen, without having to
  3048. know the current value of `FS'.
  3049.  
  3050.    This feature is still experimental, and may evolve over time.  Note
  3051. that in particular, `gawk' does not attempt to verify the sanity of the
  3052. values used in the value of `FIELDWIDTHS'.
  3053.  
  3054. 
  3055. File: gawk.info,  Node: Multiple Line,  Next: Getline,  Prev: Constant Size,  Up: Reading Files
  3056.  
  3057. Multiple-Line Records
  3058. =====================
  3059.  
  3060.    In some data bases, a single line cannot conveniently hold all the
  3061. information in one entry.  In such cases, you can use multi-line
  3062. records.
  3063.  
  3064.    The first step in doing this is to choose your data format: when
  3065. records are not defined as single lines, how do you want to define them?
  3066. What should separate records?
  3067.  
  3068.    One technique is to use an unusual character or string to separate
  3069. records.  For example, you could use the formfeed character (written
  3070. `\f' in `awk', as in C) to separate them, making each record a page of
  3071. the file.  To do this, just set the variable `RS' to `"\f"' (a string
  3072. containing the formfeed character).  Any other character could equally
  3073. well be used, as long as it won't be part of the data in a record.
  3074.  
  3075.    Another technique is to have blank lines separate records.  By a
  3076. special dispensation, an empty string as the value of `RS' indicates
  3077. that records are separated by one or more blank lines.  If you set `RS'
  3078. to the empty string, a record always ends at the first blank line
  3079. encountered.  And the next record doesn't start until the first
  3080. non-blank line that follows--no matter how many blank lines appear in a
  3081. row, they are considered one record-separator.
  3082.  
  3083.    You can achieve the same effect as `RS = ""' by assigning the string
  3084. `"\n\n+"' to `RS'. This regexp matches the newline at the end of the
  3085. record, and one or more blank lines after the record.  In addition, a
  3086. regular expression always matches the longest possible sequence when
  3087. there is a choice (*note How Much Text Matches?: Leftmost Longest.) So
  3088. the next record doesn't start until the first non-blank line that
  3089. follows--no matter how many blank lines appear in a row, they are
  3090. considered one record-separator.
  3091.  
  3092.    There is an important difference between `RS = ""' and `RS =
  3093. "\n\n+"'. In the first case, leading newlines in the input data file
  3094. are ignored, and if a file ends without extra blank lines after the
  3095. last record, the final newline is removed from the record.  In the
  3096. second case, this special processing is not done (d.c.).
  3097.  
  3098.    Now that the input is separated into records, the second step is to
  3099. separate the fields in the record.  One way to do this is to divide each
  3100. of the lines into fields in the normal manner.  This happens by default
  3101. as the result of a special feature: when `RS' is set to the empty
  3102. string, the newline character *always* acts as a field separator.  This
  3103. is in addition to whatever field separations result from `FS'.
  3104.  
  3105.    The original motivation for this special exception was probably to
  3106. provide useful behavior in the default case (i.e. `FS' is equal to
  3107. `" "').  This feature can be a problem if you really don't want the
  3108. newline character to separate fields, since there is no way to prevent
  3109. it.  However, you can work around this by using the `split' function to
  3110. break up the record manually (*note Built-in Functions for String
  3111. Manipulation: String Functions.).
  3112.  
  3113.    Another way to separate fields is to put each field on a separate
  3114. line: to do this, just set the variable `FS' to the string `"\n"'.
  3115. (This simple regular expression matches a single newline.)
  3116.  
  3117.    A practical example of a data file organized this way might be a
  3118. mailing list, where each entry is separated by blank lines.  If we have
  3119. a mailing list in a file named `addresses', that looks like this:
  3120.  
  3121.      Jane Doe
  3122.      123 Main Street
  3123.      Anywhere, SE 12345-6789
  3124.      
  3125.      John Smith
  3126.      456 Tree-lined Avenue
  3127.      Smallville, MW 98765-4321
  3128.      
  3129.      ...
  3130.  
  3131. A simple program to process this file would look like this:
  3132.  
  3133.      # addrs.awk --- simple mailing list program
  3134.      
  3135.      # Records are separated by blank lines.
  3136.      # Each line is one field.
  3137.      BEGIN { RS = "" ; FS = "\n" }
  3138.      
  3139.      {
  3140.            print "Name is:", $1
  3141.            print "Address is:", $2
  3142.            print "City and State are:", $3
  3143.            print ""
  3144.      }
  3145.  
  3146.    Running the program produces the following output:
  3147.  
  3148.      $ awk -f addrs.awk addresses
  3149.      -| Name is: Jane Doe
  3150.      -| Address is: 123 Main Street
  3151.      -| City and State are: Anywhere, SE 12345-6789
  3152.      -|
  3153.      -| Name is: John Smith
  3154.      -| Address is: 456 Tree-lined Avenue
  3155.      -| City and State are: Smallville, MW 98765-4321
  3156.      -|
  3157.      ...
  3158.  
  3159.    *Note Printing Mailing Labels: Labels Program, for a more realistic
  3160. program that deals with address lists.
  3161.  
  3162.    The following table summarizes how records are split, based on the
  3163. value of `RS'. (`==' means "is equal to.")
  3164.  
  3165. `RS == "\n"'
  3166.      Records are separated by the newline character (`\n').  In effect,
  3167.      every line in the data file is a separate record, including blank
  3168.      lines.  This is the default.
  3169.  
  3170. `RS == ANY SINGLE CHARACTER'
  3171.      Records are separated by each occurrence of the character.
  3172.      Multiple successive occurrences delimit empty records.
  3173.  
  3174. `RS == ""'
  3175.      Records are separated by runs of blank lines.  The newline
  3176.      character always serves as a field separator, in addition to
  3177.      whatever value `FS' may have. Leading and trailing newlines in a
  3178.      file are ignored.
  3179.  
  3180. `RS == REGEXP'
  3181.      Records are separated by occurrences of characters that match
  3182.      REGEXP.  Leading and trailing matches of REGEXP delimit empty
  3183.      records.
  3184.  
  3185.    In all cases, `gawk' sets `RT' to the input text that matched the
  3186. value specified by `RS'.
  3187.  
  3188. 
  3189. File: gawk.info,  Node: Getline,  Prev: Multiple Line,  Up: Reading Files
  3190.  
  3191. Explicit Input with `getline'
  3192. =============================
  3193.  
  3194.    So far we have been getting our input data from `awk''s main input
  3195. stream--either the standard input (usually your terminal, sometimes the
  3196. output from another program) or from the files specified on the command
  3197. line.  The `awk' language has a special built-in command called
  3198. `getline' that can be used to read input under your explicit control.
  3199.  
  3200. * Menu:
  3201.  
  3202. * Getline Intro::            Introduction to the `getline' function.
  3203. * Plain Getline::            Using `getline' with no arguments.
  3204. * Getline/Variable::         Using `getline' into a variable.
  3205. * Getline/File::             Using `getline' from a file.
  3206. * Getline/Variable/File::       Using `getline' into a variable from a
  3207.                                 file.
  3208. * Getline/Pipe::             Using `getline' from a pipe.
  3209. * Getline/Variable/Pipe::       Using `getline' into a variable from a
  3210.                                 pipe.
  3211. * Getline Summary::          Summary Of `getline' Variants.
  3212.  
  3213. 
  3214. File: gawk.info,  Node: Getline Intro,  Next: Plain Getline,  Prev: Getline,  Up: Getline
  3215.  
  3216. Introduction to `getline'
  3217. -------------------------
  3218.  
  3219.    This command is used in several different ways, and should *not* be
  3220. used by beginners.  It is covered here because this is the chapter on
  3221. input.  The examples that follow the explanation of the `getline'
  3222. command include material that has not been covered yet.  Therefore,
  3223. come back and study the `getline' command *after* you have reviewed the
  3224. rest of this Info file and have a good knowledge of how `awk' works.
  3225.  
  3226.    `getline' returns one if it finds a record, and zero if the end of
  3227. the file is encountered.  If there is some error in getting a record,
  3228. such as a file that cannot be opened, then `getline' returns -1.  In
  3229. this case, `gawk' sets the variable `ERRNO' to a string describing the
  3230. error that occurred.
  3231.  
  3232.    In the following examples, COMMAND stands for a string value that
  3233. represents a shell command.
  3234.  
  3235. 
  3236. File: gawk.info,  Node: Plain Getline,  Next: Getline/Variable,  Prev: Getline Intro,  Up: Getline
  3237.  
  3238. Using `getline' with No Arguments
  3239. ---------------------------------
  3240.  
  3241.    The `getline' command can be used without arguments to read input
  3242. from the current input file.  All it does in this case is read the next
  3243. input record and split it up into fields.  This is useful if you've
  3244. finished processing the current record, but you want to do some special
  3245. processing *right now* on the next record.  Here's an example:
  3246.  
  3247.      awk '{
  3248.           if ((t = index($0, "/*")) != 0) {
  3249.                # value will be "" if t is 1
  3250.                tmp = substr($0, 1, t - 1)
  3251.                u = index(substr($0, t + 2), "*/")
  3252.                while (u == 0) {
  3253.                     if (getline <= 0) {
  3254.                          m = "unexpected EOF or error"
  3255.                          m = (m ": " ERRNO)
  3256.                          print m > "/dev/stderr"
  3257.                          exit
  3258.                     }
  3259.                     t = -1
  3260.                     u = index($0, "*/")
  3261.                }
  3262.                # substr expression will be "" if */
  3263.                # occurred at end of line
  3264.                $0 = tmp substr($0, t + u + 3)
  3265.           }
  3266.           print $0
  3267.      }'
  3268.  
  3269.    This `awk' program deletes all C-style comments, `/* ...  */', from
  3270. the input.  By replacing the `print $0' with other statements, you
  3271. could perform more complicated processing on the decommented input,
  3272. like searching for matches of a regular expression.  This program has a
  3273. subtle problem--it does not work if one comment ends and another begins
  3274. on the same line.
  3275.  
  3276.    This form of the `getline' command sets `NF' (the number of fields;
  3277. *note Examining Fields: Fields.), `NR' (the number of records read so
  3278. far; *note How Input is Split into Records: Records.), `FNR' (the
  3279. number of records read from this input file), and the value of `$0'.
  3280.  
  3281.    *Note:* the new value of `$0' is used in testing the patterns of any
  3282. subsequent rules.  The original value of `$0' that triggered the rule
  3283. which executed `getline' is lost (d.c.).  By contrast, the `next'
  3284. statement reads a new record but immediately begins processing it
  3285. normally, starting with the first rule in the program.  *Note The
  3286. `next' Statement: Next Statement.
  3287.  
  3288. 
  3289. File: gawk.info,  Node: Getline/Variable,  Next: Getline/File,  Prev: Plain Getline,  Up: Getline
  3290.  
  3291. Using `getline' Into a Variable
  3292. -------------------------------
  3293.  
  3294.    You can use `getline VAR' to read the next record from `awk''s input
  3295. into the variable VAR.  No other processing is done.
  3296.  
  3297.    For example, suppose the next line is a comment, or a special string,
  3298. and you want to read it, without triggering any rules.  This form of
  3299. `getline' allows you to read that line and store it in a variable so
  3300. that the main read-a-line-and-check-each-rule loop of `awk' never sees
  3301. it.
  3302.  
  3303.    The following example swaps every two lines of input.  For example,
  3304. given:
  3305.  
  3306.      wan
  3307.      tew
  3308.      free
  3309.      phore
  3310.  
  3311. it outputs:
  3312.  
  3313.      tew
  3314.      wan
  3315.      phore
  3316.      free
  3317.  
  3318. Here's the program:
  3319.  
  3320.      awk '{
  3321.           if ((getline tmp) > 0) {
  3322.                print tmp
  3323.                print $0
  3324.           } else
  3325.                print $0
  3326.      }'
  3327.  
  3328.    The `getline' command used in this way sets only the variables `NR'
  3329. and `FNR' (and of course, VAR).  The record is not split into fields,
  3330. so the values of the fields (including `$0') and the value of `NF' do
  3331. not change.
  3332.  
  3333. 
  3334. File: gawk.info,  Node: Getline/File,  Next: Getline/Variable/File,  Prev: Getline/Variable,  Up: Getline
  3335.  
  3336. Using `getline' from a File
  3337. ---------------------------
  3338.  
  3339.    Use `getline < FILE' to read the next record from the file FILE.
  3340. Here FILE is a string-valued expression that specifies the file name.
  3341. `< FILE' is called a "redirection" since it directs input to come from
  3342. a different place.
  3343.  
  3344.    For example, the following program reads its input record from the
  3345. file `secondary.input' when it encounters a first field with a value
  3346. equal to 10 in the current input file.
  3347.  
  3348.      awk '{
  3349.          if ($1 == 10) {
  3350.               getline < "secondary.input"
  3351.               print
  3352.          } else
  3353.               print
  3354.      }'
  3355.  
  3356.    Since the main input stream is not used, the values of `NR' and
  3357. `FNR' are not changed.  But the record read is split into fields in the
  3358. normal manner, so the values of `$0' and other fields are changed.  So
  3359. is the value of `NF'.
  3360.  
  3361. 
  3362. File: gawk.info,  Node: Getline/Variable/File,  Next: Getline/Pipe,  Prev: Getline/File,  Up: Getline
  3363.  
  3364. Using `getline' Into a Variable from a File
  3365. -------------------------------------------
  3366.  
  3367.    Use `getline VAR < FILE' to read input the file FILE and put it in
  3368. the variable VAR.  As above, FILE is a string-valued expression that
  3369. specifies the file from which to read.
  3370.  
  3371.    In this version of `getline', none of the built-in variables are
  3372. changed, and the record is not split into fields.  The only variable
  3373. changed is VAR.
  3374.  
  3375.    For example, the following program copies all the input files to the
  3376. output, except for records that say `@include FILENAME'.  Such a record
  3377. is replaced by the contents of the file FILENAME.
  3378.  
  3379.      awk '{
  3380.           if (NF == 2 && $1 == "@include") {
  3381.                while ((getline line < $2) > 0)
  3382.                     print line
  3383.                close($2)
  3384.           } else
  3385.                print
  3386.      }'
  3387.  
  3388.    Note here how the name of the extra input file is not built into the
  3389. program; it is taken directly from the data, from the second field on
  3390. the `@include' line.
  3391.  
  3392.    The `close' function is called to ensure that if two identical
  3393. `@include' lines appear in the input, the entire specified file is
  3394. included twice.  *Note Closing Input and Output Files and Pipes: Close
  3395. Files And Pipes.
  3396.  
  3397.    One deficiency of this program is that it does not process nested
  3398. `@include' statements (`@include' statements in included files) the way
  3399. a true macro preprocessor would.  *Note An Easy Way to Use Library
  3400. Functions: Igawk Program, for a program that does handle nested
  3401. `@include' statements.
  3402.  
  3403. 
  3404. File: gawk.info,  Node: Getline/Pipe,  Next: Getline/Variable/Pipe,  Prev: Getline/Variable/File,  Up: Getline
  3405.  
  3406. Using `getline' from a Pipe
  3407. ---------------------------
  3408.  
  3409.    You can pipe the output of a command into `getline', using `COMMAND
  3410. | getline'.  In this case, the string COMMAND is run as a shell command
  3411. and its output is piped into `awk' to be used as input.  This form of
  3412. `getline' reads one record at a time from the pipe.
  3413.  
  3414.    For example, the following program copies its input to its output,
  3415. except for lines that begin with `@execute', which are replaced by the
  3416. output produced by running the rest of the line as a shell command:
  3417.  
  3418.      awk '{
  3419.           if ($1 == "@execute") {
  3420.                tmp = substr($0, 10)
  3421.                while ((tmp | getline) > 0)
  3422.                     print
  3423.                close(tmp)
  3424.           } else
  3425.                print
  3426.      }'
  3427.  
  3428. The `close' function is called to ensure that if two identical
  3429. `@execute' lines appear in the input, the command is run for each one.
  3430. *Note Closing Input and Output Files and Pipes: Close Files And Pipes.
  3431.  
  3432.    Given the input:
  3433.  
  3434.      foo
  3435.      bar
  3436.      baz
  3437.      @execute who
  3438.      bletch
  3439.  
  3440. the program might produce:
  3441.  
  3442.      foo
  3443.      bar
  3444.      baz
  3445.      arnold     ttyv0   Jul 13 14:22
  3446.      miriam     ttyp0   Jul 13 14:23     (murphy:0)
  3447.      bill       ttyp1   Jul 13 14:23     (murphy:0)
  3448.      bletch
  3449.  
  3450. Notice that this program ran the command `who' and printed the result.
  3451. (If you try this program yourself, you will of course get different
  3452. results, showing you who is logged in on your system.)
  3453.  
  3454.    This variation of `getline' splits the record into fields, sets the
  3455. value of `NF' and recomputes the value of `$0'.  The values of `NR' and
  3456. `FNR' are not changed.
  3457.  
  3458. 
  3459. File: gawk.info,  Node: Getline/Variable/Pipe,  Next: Getline Summary,  Prev: Getline/Pipe,  Up: Getline
  3460.  
  3461. Using `getline' Into a Variable from a Pipe
  3462. -------------------------------------------
  3463.  
  3464.    When you use `COMMAND | getline VAR', the output of the command
  3465. COMMAND is sent through a pipe to `getline' and into the variable VAR.
  3466. For example, the following program reads the current date and time into
  3467. the variable `current_time', using the `date' utility, and then prints
  3468. it.
  3469.  
  3470.      awk 'BEGIN {
  3471.           "date" | getline current_time
  3472.           close("date")
  3473.           print "Report printed on " current_time
  3474.      }'
  3475.  
  3476.    In this version of `getline', none of the built-in variables are
  3477. changed, and the record is not split into fields.
  3478.  
  3479. 
  3480. File: gawk.info,  Node: Getline Summary,  Prev: Getline/Variable/Pipe,  Up: Getline
  3481.  
  3482. Summary of `getline' Variants
  3483. -----------------------------
  3484.  
  3485.    With all the forms of `getline', even though `$0' and `NF', may be
  3486. updated, the record will not be tested against all the patterns in the
  3487. `awk' program, in the way that would happen if the record were read
  3488. normally by the main processing loop of `awk'.  However the new record
  3489. is tested against any subsequent rules.
  3490.  
  3491.    Many `awk' implementations limit the number of pipelines an `awk'
  3492. program may have open to just one!  In `gawk', there is no such limit.
  3493. You can open as many pipelines as the underlying operating system will
  3494. permit.
  3495.  
  3496.    The following table summarizes the six variants of `getline',
  3497. listing which built-in variables are set by each one.
  3498.  
  3499. `getline'
  3500.      sets `$0', `NF', `FNR', and `NR'.
  3501.  
  3502. `getline VAR'
  3503.      sets VAR, `FNR', and `NR'.
  3504.  
  3505. `getline < FILE'
  3506.      sets `$0', and `NF'.
  3507.  
  3508. `getline VAR < FILE'
  3509.      sets VAR.
  3510.  
  3511. `COMMAND | getline'
  3512.      sets `$0', and `NF'.
  3513.  
  3514. `COMMAND | getline VAR'
  3515.      sets VAR.
  3516.  
  3517. 
  3518. File: gawk.info,  Node: Printing,  Next: Expressions,  Prev: Reading Files,  Up: Top
  3519.  
  3520. Printing Output
  3521. ***************
  3522.  
  3523.    One of the most common actions is to "print", or output, some or all
  3524. of the input.  You use the `print' statement for simple output.  You
  3525. use the `printf' statement for fancier formatting.  Both are described
  3526. in this chapter.
  3527.  
  3528. * Menu:
  3529.  
  3530. * Print::                       The `print' statement.
  3531. * Print Examples::              Simple examples of `print' statements.
  3532. * Output Separators::           The output separators and how to change them.
  3533. * OFMT::                        Controlling Numeric Output With `print'.
  3534. * Printf::                      The `printf' statement.
  3535. * Redirection::                 How to redirect output to multiple files and
  3536.                                 pipes.
  3537. * Special Files::               File name interpretation in `gawk'.
  3538.                                 `gawk' allows access to inherited file
  3539.                                 descriptors.
  3540. * Close Files And Pipes::       Closing Input and Output Files and Pipes.
  3541.  
  3542. 
  3543. File: gawk.info,  Node: Print,  Next: Print Examples,  Prev: Printing,  Up: Printing
  3544.  
  3545. The `print' Statement
  3546. =====================
  3547.  
  3548.    The `print' statement does output with simple, standardized
  3549. formatting.  You specify only the strings or numbers to be printed, in a
  3550. list separated by commas.  They are output, separated by single spaces,
  3551. followed by a newline.  The statement looks like this:
  3552.  
  3553.      print ITEM1, ITEM2, ...
  3554.  
  3555. The entire list of items may optionally be enclosed in parentheses.  The
  3556. parentheses are necessary if any of the item expressions uses the `>'
  3557. relational operator; otherwise it could be confused with a redirection
  3558. (*note Redirecting Output of `print' and `printf': Redirection.).
  3559.  
  3560.    The items to be printed can be constant strings or numbers, fields
  3561. of the current record (such as `$1'), variables, or any `awk'
  3562. expressions.  Numeric values are converted to strings, and then printed.
  3563.  
  3564.    The `print' statement is completely general for computing *what*
  3565. values to print. However, with two exceptions, you cannot specify *how*
  3566. to print them--how many columns, whether to use exponential notation or
  3567. not, and so on.  (For the exceptions, *note Output Separators::., and
  3568. *Note Controlling Numeric Output with `print': OFMT.) For that, you
  3569. need the `printf' statement (*note Using `printf' Statements for
  3570. Fancier Printing: Printf.).
  3571.  
  3572.    The simple statement `print' with no items is equivalent to `print
  3573. $0': it prints the entire current record.  To print a blank line, use
  3574. `print ""', where `""' is the empty string.
  3575.  
  3576.    To print a fixed piece of text, use a string constant such as
  3577. `"Don't Panic"' as one item.  If you forget to use the double-quote
  3578. characters, your text will be taken as an `awk' expression, and you
  3579. will probably get an error.  Keep in mind that a space is printed
  3580. between any two items.
  3581.  
  3582.    Each `print' statement makes at least one line of output.  But it
  3583. isn't limited to one line.  If an item value is a string that contains a
  3584. newline, the newline is output along with the rest of the string.  A
  3585. single `print' can make any number of lines this way.
  3586.  
  3587. 
  3588. File: gawk.info,  Node: Print Examples,  Next: Output Separators,  Prev: Print,  Up: Printing
  3589.  
  3590. Examples of `print' Statements
  3591. ==============================
  3592.  
  3593.    Here is an example of printing a string that contains embedded
  3594. newlines (the `\n' is an escape sequence, used to represent the newline
  3595. character; see *Note Escape Sequences::):
  3596.  
  3597.      $ awk 'BEGIN { print "line one\nline two\nline three" }'
  3598.      -| line one
  3599.      -| line two
  3600.      -| line three
  3601.  
  3602.    Here is an example that prints the first two fields of each input
  3603. record, with a space between them:
  3604.  
  3605.      $ awk '{ print $1, $2 }' inventory-shipped
  3606.      -| Jan 13
  3607.      -| Feb 15
  3608.      -| Mar 15
  3609.      ...
  3610.  
  3611.    A common mistake in using the `print' statement is to omit the comma
  3612. between two items.  This often has the effect of making the items run
  3613. together in the output, with no space.  The reason for this is that
  3614. juxtaposing two string expressions in `awk' means to concatenate them.
  3615. Here is the same program, without the comma:
  3616.  
  3617.      $ awk '{ print $1 $2 }' inventory-shipped
  3618.      -| Jan13
  3619.      -| Feb15
  3620.      -| Mar15
  3621.      ...
  3622.  
  3623.    To someone unfamiliar with the file `inventory-shipped', neither
  3624. example's output makes much sense.  A heading line at the beginning
  3625. would make it clearer.  Let's add some headings to our table of months
  3626. (`$1') and green crates shipped (`$2').  We do this using the `BEGIN'
  3627. pattern (*note The `BEGIN' and `END' Special Patterns: BEGIN/END.) to
  3628. force the headings to be printed only once:
  3629.  
  3630.      awk 'BEGIN {  print "Month Crates"
  3631.                    print "----- ------" }
  3632.                 {  print $1, $2 }' inventory-shipped
  3633.  
  3634. Did you already guess what happens? When run, the program prints the
  3635. following:
  3636.  
  3637.      Month Crates
  3638.      ----- ------
  3639.      Jan 13
  3640.      Feb 15
  3641.      Mar 15
  3642.      ...
  3643.  
  3644. The headings and the table data don't line up!  We can fix this by
  3645. printing some spaces between the two fields:
  3646.  
  3647.      awk 'BEGIN { print "Month Crates"
  3648.                   print "----- ------" }
  3649.                 { print $1, "     ", $2 }' inventory-shipped
  3650.  
  3651.    You can imagine that this way of lining up columns can get pretty
  3652. complicated when you have many columns to fix.  Counting spaces for two
  3653. or three columns can be simple, but more than this and you can get lost
  3654. quite easily.  This is why the `printf' statement was created (*note
  3655. Using `printf' Statements for Fancier Printing: Printf.); one of its
  3656. specialties is lining up columns of data.
  3657.  
  3658.    As a side point, you can continue either a `print' or `printf'
  3659. statement simply by putting a newline after any comma (*note `awk'
  3660. Statements Versus Lines: Statements/Lines.).
  3661.  
  3662. 
  3663. File: gawk.info,  Node: Output Separators,  Next: OFMT,  Prev: Print Examples,  Up: Printing
  3664.  
  3665. Output Separators
  3666. =================
  3667.  
  3668.    As mentioned previously, a `print' statement contains a list of
  3669. items, separated by commas.  In the output, the items are normally
  3670. separated by single spaces.  This need not be the case; a single space
  3671. is only the default.  You can specify any string of characters to use
  3672. as the "output field separator" by setting the built-in variable `OFS'.
  3673. The initial value of this variable is the string `" "', that is, a
  3674. single space.
  3675.  
  3676.    The output from an entire `print' statement is called an "output
  3677. record".  Each `print' statement outputs one output record and then
  3678. outputs a string called the "output record separator".  The built-in
  3679. variable `ORS' specifies this string.  The initial value of `ORS' is
  3680. the string `"\n"', i.e. a newline character; thus, normally each
  3681. `print' statement makes a separate line.
  3682.  
  3683.    You can change how output fields and records are separated by
  3684. assigning new values to the variables `OFS' and/or `ORS'.  The usual
  3685. place to do this is in the `BEGIN' rule (*note The `BEGIN' and `END'
  3686. Special Patterns: BEGIN/END.), so that it happens before any input is
  3687. processed.  You may also do this with assignments on the command line,
  3688. before the names of your input files, or using the `-v' command line
  3689. option (*note Command Line Options: Options.).
  3690.  
  3691.    The following example prints the first and second fields of each
  3692. input record separated by a semicolon, with a blank line added after
  3693. each line:
  3694.  
  3695.      $ awk 'BEGIN { OFS = ";"; ORS = "\n\n" }
  3696.      >            { print $1, $2 }' BBS-list
  3697.      -| aardvark;555-5553
  3698.      -|
  3699.      -| alpo-net;555-3412
  3700.      -|
  3701.      -| barfly;555-7685
  3702.      ...
  3703.  
  3704.    If the value of `ORS' does not contain a newline, all your output
  3705. will be run together on a single line, unless you output newlines some
  3706. other way.
  3707.  
  3708. 
  3709. File: gawk.info,  Node: OFMT,  Next: Printf,  Prev: Output Separators,  Up: Printing
  3710.  
  3711. Controlling Numeric Output with `print'
  3712. =======================================
  3713.  
  3714.    When you use the `print' statement to print numeric values, `awk'
  3715. internally converts the number to a string of characters, and prints
  3716. that string.  `awk' uses the `sprintf' function to do this conversion
  3717. (*note Built-in Functions for String Manipulation: String Functions.).
  3718. For now, it suffices to say that the `sprintf' function accepts a
  3719. "format specification" that tells it how to format numbers (or
  3720. strings), and that there are a number of different ways in which
  3721. numbers can be formatted.  The different format specifications are
  3722. discussed more fully in *Note Format-Control Letters: Control Letters.
  3723.  
  3724.    The built-in variable `OFMT' contains the default format
  3725. specification that `print' uses with `sprintf' when it wants to convert
  3726. a number to a string for printing.  The default value of `OFMT' is
  3727. `"%.6g"'.  By supplying different format specifications as the value of
  3728. `OFMT', you can change how `print' will print your numbers.  As a brief
  3729. example:
  3730.  
  3731.      $ awk 'BEGIN {
  3732.      >   OFMT = "%.0f"  # print numbers as integers (rounds)
  3733.      >   print 17.23 }'
  3734.      -| 17
  3735.  
  3736. According to the POSIX standard, `awk''s behavior will be undefined if
  3737. `OFMT' contains anything but a floating point conversion specification
  3738. (d.c.).
  3739.  
  3740. 
  3741. File: gawk.info,  Node: Printf,  Next: Redirection,  Prev: OFMT,  Up: Printing
  3742.  
  3743. Using `printf' Statements for Fancier Printing
  3744. ==============================================
  3745.  
  3746.    If you want more precise control over the output format than `print'
  3747. gives you, use `printf'.  With `printf' you can specify the width to
  3748. use for each item, and you can specify various formatting choices for
  3749. numbers (such as what radix to use, whether to print an exponent,
  3750. whether to print a sign, and how many digits to print after the decimal
  3751. point).  You do this by supplying a string, called the "format string",
  3752. which controls how and where to print the other arguments.
  3753.  
  3754. * Menu:
  3755.  
  3756. * Basic Printf::                Syntax of the `printf' statement.
  3757. * Control Letters::             Format-control letters.
  3758. * Format Modifiers::            Format-specification modifiers.
  3759. * Printf Examples::             Several examples.
  3760.  
  3761. 
  3762. File: gawk.info,  Node: Basic Printf,  Next: Control Letters,  Prev: Printf,  Up: Printf
  3763.  
  3764. Introduction to the `printf' Statement
  3765. --------------------------------------
  3766.  
  3767.    The `printf' statement looks like this:
  3768.  
  3769.      printf FORMAT, ITEM1, ITEM2, ...
  3770.  
  3771. The entire list of arguments may optionally be enclosed in parentheses.
  3772. The parentheses are necessary if any of the item expressions use the
  3773. `>' relational operator; otherwise it could be confused with a
  3774. redirection (*note Redirecting Output of `print' and `printf':
  3775. Redirection.).
  3776.  
  3777.    The difference between `printf' and `print' is the FORMAT argument.
  3778. This is an expression whose value is taken as a string; it specifies
  3779. how to output each of the other arguments.  It is called the "format
  3780. string".
  3781.  
  3782.    The format string is very similar to that in the ANSI C library
  3783. function `printf'.  Most of FORMAT is text to be output verbatim.
  3784. Scattered among this text are "format specifiers", one per item.  Each
  3785. format specifier says to output the next item in the argument list at
  3786. that place in the format.
  3787.  
  3788.    The `printf' statement does not automatically append a newline to its
  3789. output.  It outputs only what the format string specifies.  So if you
  3790. want a newline, you must include one in the format string.  The output
  3791. separator variables `OFS' and `ORS' have no effect on `printf'
  3792. statements. For example:
  3793.  
  3794.      BEGIN {
  3795.         ORS = "\nOUCH!\n"; OFS = "!"
  3796.         msg = "Don't Panic!"; printf "%s\n", msg
  3797.      }
  3798.  
  3799.    This program still prints the familiar `Don't Panic!' message.
  3800.  
  3801. 
  3802. File: gawk.info,  Node: Control Letters,  Next: Format Modifiers,  Prev: Basic Printf,  Up: Printf
  3803.  
  3804. Format-Control Letters
  3805. ----------------------
  3806.  
  3807.    A format specifier starts with the character `%' and ends with a
  3808. "format-control letter"; it tells the `printf' statement how to output
  3809. one item.  (If you actually want to output a `%', write `%%'.)  The
  3810. format-control letter specifies what kind of value to print.  The rest
  3811. of the format specifier is made up of optional "modifiers" which are
  3812. parameters to use, such as the field width.
  3813.  
  3814.    Here is a list of the format-control letters:
  3815.  
  3816. `c'
  3817.      This prints a number as an ASCII character.  Thus, `printf "%c",
  3818.      65' outputs the letter `A'.  The output for a string value is the
  3819.      first character of the string.
  3820.  
  3821. `d'
  3822. `i'
  3823.      These are equivalent. They both print a decimal integer.  The `%i'
  3824.      specification is for compatibility with ANSI C.
  3825.  
  3826. `e'
  3827. `E'
  3828.      This prints a number in scientific (exponential) notation.  For
  3829.      example,
  3830.  
  3831.           printf "%4.3e\n", 1950
  3832.  
  3833.      prints `1.950e+03', with a total of four significant figures of
  3834.      which three follow the decimal point.  The `4.3' are modifiers,
  3835.      discussed below. `%E' uses `E' instead of `e' in the output.
  3836.  
  3837. `f'
  3838.      This prints a number in floating point notation.  For example,
  3839.  
  3840.           printf "%4.3f", 1950
  3841.  
  3842.      prints `1950.000', with a total of four significant figures of
  3843.      which three follow the decimal point.  The `4.3' are modifiers,
  3844.      discussed below.
  3845.  
  3846. `g'
  3847. `G'
  3848.      This prints a number in either scientific notation or floating
  3849.      point notation, whichever uses fewer characters. If the result is
  3850.      printed in scientific notation, `%G' uses `E' instead of `e'.
  3851.  
  3852. `o'
  3853.      This prints an unsigned octal integer.  (In octal, or base-eight
  3854.      notation, the digits run from `0' to `7'; the decimal number eight
  3855.      is represented as `10' in octal.)
  3856.  
  3857. `s'
  3858.      This prints a string.
  3859.  
  3860. `x'
  3861. `X'
  3862.      This prints an unsigned hexadecimal integer.  (In hexadecimal, or
  3863.      base-16 notation, the digits are `0' through `9' and `a' through
  3864.      `f'.  The hexadecimal digit `f' represents the decimal number 15.)
  3865.      `%X' uses the letters `A' through `F' instead of `a' through `f'.
  3866.  
  3867. `%'
  3868.      This isn't really a format-control letter, but it does have a
  3869.      meaning when used after a `%': the sequence `%%' outputs one `%'.
  3870.      It does not consume an argument, and it ignores any modifiers.
  3871.  
  3872.    When using the integer format-control letters for values that are
  3873. outside the range of a C `long' integer, `gawk' will switch to the `%g'
  3874. format specifier. Other versions of `awk' may print invalid values, or
  3875. do something else entirely (d.c.).
  3876.  
  3877. 
  3878. File: gawk.info,  Node: Format Modifiers,  Next: Printf Examples,  Prev: Control Letters,  Up: Printf
  3879.  
  3880. Modifiers for `printf' Formats
  3881. ------------------------------
  3882.  
  3883.    A format specification can also include "modifiers" that can control
  3884. how much of the item's value is printed and how much space it gets.  The
  3885. modifiers come between the `%' and the format-control letter.  In the
  3886. examples below, we use the bullet symbol "*" to represent spaces in the
  3887. output. Here are the possible modifiers, in the order in which they may
  3888. appear:
  3889.  
  3890. `-'
  3891.      The minus sign, used before the width modifier (see below), says
  3892.      to left-justify the argument within its specified width.  Normally
  3893.      the argument is printed right-justified in the specified width.
  3894.      Thus,
  3895.  
  3896.           printf "%-4s", "foo"
  3897.  
  3898.      prints `foo*'.
  3899.  
  3900. `SPACE'
  3901.      For numeric conversions, prefix positive values with a space, and
  3902.      negative values with a minus sign.
  3903.  
  3904. `+'
  3905.      The plus sign, used before the width modifier (see below), says to
  3906.      always supply a sign for numeric conversions, even if the data to
  3907.      be formatted is positive. The `+' overrides the space modifier.
  3908.  
  3909. `#'
  3910.      Use an "alternate form" for certain control letters.  For `%o',
  3911.      supply a leading zero.  For `%x', and `%X', supply a leading `0x'
  3912.      or `0X' for a non-zero result.  For `%e', `%E', and `%f', the
  3913.      result will always contain a decimal point.  For `%g', and `%G',
  3914.      trailing zeros are not removed from the result.
  3915.  
  3916. `0'
  3917.      A leading `0' (zero) acts as a flag, that indicates output should
  3918.      be padded with zeros instead of spaces.  This applies even to
  3919.      non-numeric output formats (d.c.).  This flag only has an effect
  3920.      when the field width is wider than the value to be printed.
  3921.  
  3922. `WIDTH'
  3923.      This is a number specifying the desired minimum width of a field.
  3924.      Inserting any number between the `%' sign and the format control
  3925.      character forces the field to be expanded to this width.  The
  3926.      default way to do this is to pad with spaces on the left.  For
  3927.      example,
  3928.  
  3929.           printf "%4s", "foo"
  3930.  
  3931.      prints `*foo'.
  3932.  
  3933.      The value of WIDTH is a minimum width, not a maximum.  If the item
  3934.      value requires more than WIDTH characters, it can be as wide as
  3935.      necessary.  Thus,
  3936.  
  3937.           printf "%4s", "foobar"
  3938.  
  3939.      prints `foobar'.
  3940.  
  3941.      Preceding the WIDTH with a minus sign causes the output to be
  3942.      padded with spaces on the right, instead of on the left.
  3943.  
  3944. `.PREC'
  3945.      This is a number that specifies the precision to use when printing.
  3946.      For the `e', `E', and `f' formats, this specifies the number of
  3947.      digits you want printed to the right of the decimal point.  For
  3948.      the `g', and `G' formats, it specifies the maximum number of
  3949.      significant digits.  For the `d', `o', `i', `u', `x', and `X'
  3950.      formats, it specifies the minimum number of digits to print.  For
  3951.      a string, it specifies the maximum number of characters from the
  3952.      string that should be printed.  Thus,
  3953.  
  3954.           printf "%.4s", "foobar"
  3955.  
  3956.      prints `foob'.
  3957.  
  3958.    The C library `printf''s dynamic WIDTH and PREC capability (for
  3959. example, `"%*.*s"') is supported.  Instead of supplying explicit WIDTH
  3960. and/or PREC values in the format string, you pass them in the argument
  3961. list.  For example:
  3962.  
  3963.      w = 5
  3964.      p = 3
  3965.      s = "abcdefg"
  3966.      printf "%*.*s\n", w, p, s
  3967.  
  3968. is exactly equivalent to
  3969.  
  3970.      s = "abcdefg"
  3971.      printf "%5.3s\n", s
  3972.  
  3973. Both programs output `**abc'.
  3974.  
  3975.    Earlier versions of `awk' did not support this capability.  If you
  3976. must use such a version, you may simulate this feature by using
  3977. concatenation to build up the format string, like so:
  3978.  
  3979.      w = 5
  3980.      p = 3
  3981.      s = "abcdefg"
  3982.      printf "%" w "." p "s\n", s
  3983.  
  3984. This is not particularly easy to read, but it does work.
  3985.  
  3986.    C programmers may be used to supplying additional `l' and `h' flags
  3987. in `printf' format strings. These are not valid in `awk'.  Most `awk'
  3988. implementations silently ignore these flags.  If `--lint' is provided
  3989. on the command line (*note Command Line Options: Options.), `gawk' will
  3990. warn about their use. If `--posix' is supplied, their use is a fatal
  3991. error.
  3992.  
  3993. 
  3994. File: gawk.info,  Node: Printf Examples,  Prev: Format Modifiers,  Up: Printf
  3995.  
  3996. Examples Using `printf'
  3997. -----------------------
  3998.  
  3999.    Here is how to use `printf' to make an aligned table:
  4000.  
  4001.      awk '{ printf "%-10s %s\n", $1, $2 }' BBS-list
  4002.  
  4003. prints the names of bulletin boards (`$1') of the file `BBS-list' as a
  4004. string of 10 characters, left justified.  It also prints the phone
  4005. numbers (`$2') afterward on the line.  This produces an aligned
  4006. two-column table of names and phone numbers:
  4007.  
  4008.      $ awk '{ printf "%-10s %s\n", $1, $2 }' BBS-list
  4009.      -| aardvark   555-5553
  4010.      -| alpo-net   555-3412
  4011.      -| barfly     555-7685
  4012.      -| bites      555-1675
  4013.      -| camelot    555-0542
  4014.      -| core       555-2912
  4015.      -| fooey      555-1234
  4016.      -| foot       555-6699
  4017.      -| macfoo     555-6480
  4018.      -| sdace      555-3430
  4019.      -| sabafoo    555-2127
  4020.  
  4021.    Did you notice that we did not specify that the phone numbers be
  4022. printed as numbers?  They had to be printed as strings because the
  4023. numbers are separated by a dash.  If we had tried to print the phone
  4024. numbers as numbers, all we would have gotten would have been the first
  4025. three digits, `555'.  This would have been pretty confusing.
  4026.  
  4027.    We did not specify a width for the phone numbers because they are the
  4028. last things on their lines.  We don't need to put spaces after them.
  4029.  
  4030.    We could make our table look even nicer by adding headings to the
  4031. tops of the columns.  To do this, we use the `BEGIN' pattern (*note The
  4032. `BEGIN' and `END' Special Patterns: BEGIN/END.) to force the header to
  4033. be printed only once, at the beginning of the `awk' program:
  4034.  
  4035.      awk 'BEGIN { print "Name      Number"
  4036.                   print "----      ------" }
  4037.           { printf "%-10s %s\n", $1, $2 }' BBS-list
  4038.  
  4039.    Did you notice that we mixed `print' and `printf' statements in the
  4040. above example?  We could have used just `printf' statements to get the
  4041. same results:
  4042.  
  4043.      awk 'BEGIN { printf "%-10s %s\n", "Name", "Number"
  4044.                   printf "%-10s %s\n", "----", "------" }
  4045.           { printf "%-10s %s\n", $1, $2 }' BBS-list
  4046.  
  4047. By printing each column heading with the same format specification used
  4048. for the elements of the column, we have made sure that the headings are
  4049. aligned just like the columns.
  4050.  
  4051.    The fact that the same format specification is used three times can
  4052. be emphasized by storing it in a variable, like this:
  4053.  
  4054.      awk 'BEGIN { format = "%-10s %s\n"
  4055.                   printf format, "Name", "Number"
  4056.                   printf format, "----", "------" }
  4057.           { printf format, $1, $2 }' BBS-list
  4058.  
  4059.    See if you can use the `printf' statement to line up the headings and
  4060. table data for our `inventory-shipped' example covered earlier in the
  4061. section on the `print' statement (*note The `print' Statement: Print.).
  4062.  
  4063. 
  4064. File: gawk.info,  Node: Redirection,  Next: Special Files,  Prev: Printf,  Up: Printing
  4065.  
  4066. Redirecting Output of `print' and `printf'
  4067. ==========================================
  4068.  
  4069.    So far we have been dealing only with output that prints to the
  4070. standard output, usually your terminal.  Both `print' and `printf' can
  4071. also send their output to other places.  This is called "redirection".
  4072.  
  4073.    A redirection appears after the `print' or `printf' statement.
  4074. Redirections in `awk' are written just like redirections in shell
  4075. commands, except that they are written inside the `awk' program.
  4076.  
  4077.    There are three forms of output redirection: output to a file,
  4078. output appended to a file, and output through a pipe to another command.
  4079. They are all shown for the `print' statement, but they work identically
  4080. for `printf' also.
  4081.  
  4082. `print ITEMS > OUTPUT-FILE'
  4083.      This type of redirection prints the items into the output file
  4084.      OUTPUT-FILE.  The file name OUTPUT-FILE can be any expression.
  4085.      Its value is changed to a string and then used as a file name
  4086.      (*note Expressions::.).
  4087.  
  4088.      When this type of redirection is used, the OUTPUT-FILE is erased
  4089.      before the first output is written to it.  Subsequent writes to
  4090.      the same OUTPUT-FILE do not erase OUTPUT-FILE, but append to it.
  4091.      If OUTPUT-FILE does not exist, then it is created.
  4092.  
  4093.      For example, here is how an `awk' program can write a list of BBS
  4094.      names to a file `name-list' and a list of phone numbers to a file
  4095.      `phone-list'.  Each output file contains one name or number per
  4096.      line.
  4097.  
  4098.           $ awk '{ print $2 > "phone-list"
  4099.           >        print $1 > "name-list" }' BBS-list
  4100.           $ cat phone-list
  4101.           -| 555-5553
  4102.           -| 555-3412
  4103.           ...
  4104.           $ cat name-list
  4105.           -| aardvark
  4106.           -| alpo-net
  4107.           ...
  4108.  
  4109. `print ITEMS >> OUTPUT-FILE'
  4110.      This type of redirection prints the items into the pre-existing
  4111.      output file OUTPUT-FILE.  The difference between this and the
  4112.      single-`>' redirection is that the old contents (if any) of
  4113.      OUTPUT-FILE are not erased.  Instead, the `awk' output is appended
  4114.      to the file.  If OUTPUT-FILE does not exist, then it is created.
  4115.  
  4116. `print ITEMS | COMMAND'
  4117.      It is also possible to send output to another program through a
  4118.      pipe instead of into a file.   This type of redirection opens a
  4119.      pipe to COMMAND and writes the values of ITEMS through this pipe,
  4120.      to another process created to execute COMMAND.
  4121.  
  4122.      The redirection argument COMMAND is actually an `awk' expression.
  4123.      Its value is converted to a string, whose contents give the shell
  4124.      command to be run.
  4125.  
  4126.      For example, this produces two files, one unsorted list of BBS
  4127.      names and one list sorted in reverse alphabetical order:
  4128.  
  4129.           awk '{ print $1 > "names.unsorted"
  4130.                  command = "sort -r > names.sorted"
  4131.                  print $1 | command }' BBS-list
  4132.  
  4133.      Here the unsorted list is written with an ordinary redirection
  4134.      while the sorted list is written by piping through the `sort'
  4135.      utility.
  4136.  
  4137.      This example uses redirection to mail a message to a mailing list
  4138.      `bug-system'.  This might be useful when trouble is encountered in
  4139.      an `awk' script run periodically for system maintenance.
  4140.  
  4141.           report = "mail bug-system"
  4142.           print "Awk script failed:", $0 | report
  4143.           m = ("at record number " FNR " of " FILENAME)
  4144.           print m | report
  4145.           close(report)
  4146.  
  4147.      The message is built using string concatenation and saved in the
  4148.      variable `m'.  It is then sent down the pipeline to the `mail'
  4149.      program.
  4150.  
  4151.      We call the `close' function here because it's a good idea to close
  4152.      the pipe as soon as all the intended output has been sent to it.
  4153.      *Note Closing Input and Output Files and Pipes: Close Files And
  4154.      Pipes, for more information on this.  This example also
  4155.      illustrates the use of a variable to represent a FILE or COMMAND:
  4156.      it is not necessary to always use a string constant.  Using a
  4157.      variable is generally a good idea, since `awk' requires you to
  4158.      spell the string value identically every time.
  4159.  
  4160.    Redirecting output using `>', `>>', or `|' asks the system to open a
  4161. file or pipe only if the particular FILE or COMMAND you've specified
  4162. has not already been written to by your program, or if it has been
  4163. closed since it was last written to.
  4164.  
  4165.    Many `awk' implementations limit the number of pipelines an `awk'
  4166. program may have open to just one!  In `gawk', there is no such limit.
  4167. You can open as many pipelines as the underlying operating system will
  4168. permit.
  4169.  
  4170. 
  4171. File: gawk.info,  Node: Special Files,  Next: Close Files And Pipes,  Prev: Redirection,  Up: Printing
  4172.  
  4173. Special File Names in `gawk'
  4174. ============================
  4175.  
  4176.    Running programs conventionally have three input and output streams
  4177. already available to them for reading and writing.  These are known as
  4178. the "standard input", "standard output", and "standard error output".
  4179. These streams are, by default, connected to your terminal, but they are
  4180. often redirected with the shell, via the `<', `<<', `>', `>>', `>&' and
  4181. `|' operators.  Standard error is typically used for writing error
  4182. messages; the reason we have two separate streams, standard output and
  4183. standard error, is so that they can be redirected separately.
  4184.  
  4185.    In other implementations of `awk', the only way to write an error
  4186. message to standard error in an `awk' program is as follows:
  4187.  
  4188.      print "Serious error detected!" | "cat 1>&2"
  4189.  
  4190. This works by opening a pipeline to a shell command which can access the
  4191. standard error stream which it inherits from the `awk' process.  This
  4192. is far from elegant, and is also inefficient, since it requires a
  4193. separate process.  So people writing `awk' programs often neglect to do
  4194. this.  Instead, they send the error messages to the terminal, like this:
  4195.  
  4196.      print "Serious error detected!" > "/dev/tty"
  4197.  
  4198. This usually has the same effect, but not always: although the standard
  4199. error stream is usually the terminal, it can be redirected, and when
  4200. that happens, writing to the terminal is not correct.  In fact, if
  4201. `awk' is run from a background job, it may not have a terminal at all.
  4202. Then opening `/dev/tty' will fail.
  4203.  
  4204.    `gawk' provides special file names for accessing the three standard
  4205. streams.  When you redirect input or output in `gawk', if the file name
  4206. matches one of these special names, then `gawk' directly uses the
  4207. stream it stands for.
  4208.  
  4209. `/dev/stdin'
  4210.      The standard input (file descriptor 0).
  4211.  
  4212. `/dev/stdout'
  4213.      The standard output (file descriptor 1).
  4214.  
  4215. `/dev/stderr'
  4216.      The standard error output (file descriptor 2).
  4217.  
  4218. `/dev/fd/N'
  4219.      The file associated with file descriptor N.  Such a file must have
  4220.      been opened by the program initiating the `awk' execution
  4221.      (typically the shell).  Unless you take special pains in the shell
  4222.      from which you invoke `gawk', only descriptors 0, 1 and 2 are
  4223.      available.
  4224.  
  4225.    The file names `/dev/stdin', `/dev/stdout', and `/dev/stderr' are
  4226. aliases for `/dev/fd/0', `/dev/fd/1', and `/dev/fd/2', respectively,
  4227. but they are more self-explanatory.
  4228.  
  4229.    The proper way to write an error message in a `gawk' program is to
  4230. use `/dev/stderr', like this:
  4231.  
  4232.      print "Serious error detected!" > "/dev/stderr"
  4233.  
  4234.    `gawk' also provides special file names that give access to
  4235. information about the running `gawk' process.  Each of these "files"
  4236. provides a single record of information.  To read them more than once,
  4237. you must first close them with the `close' function (*note Closing
  4238. Input and Output Files and Pipes: Close Files And Pipes.).  The
  4239. filenames are:
  4240.  
  4241. `/dev/pid'
  4242.      Reading this file returns the process ID of the current process,
  4243.      in decimal, terminated with a newline.
  4244.  
  4245. `/dev/ppid'
  4246.      Reading this file returns the parent process ID of the current
  4247.      process, in decimal, terminated with a newline.
  4248.  
  4249. `/dev/pgrpid'
  4250.      Reading this file returns the process group ID of the current
  4251.      process, in decimal, terminated with a newline.
  4252.  
  4253. `/dev/user'
  4254.      Reading this file returns a single record terminated with a
  4255.      newline.  The fields are separated with spaces.  The fields
  4256.      represent the following information:
  4257.  
  4258.     `$1'
  4259.           The return value of the `getuid' system call (the real user
  4260.           ID number).
  4261.  
  4262.     `$2'
  4263.           The return value of the `geteuid' system call (the effective
  4264.           user ID number).
  4265.  
  4266.     `$3'
  4267.           The return value of the `getgid' system call (the real group
  4268.           ID number).
  4269.  
  4270.     `$4'
  4271.           The return value of the `getegid' system call (the effective
  4272.           group ID number).
  4273.  
  4274.      If there are any additional fields, they are the group IDs
  4275.      returned by `getgroups' system call.  (Multiple groups may not be
  4276.      supported on all systems.)
  4277.  
  4278.    These special file names may be used on the command line as data
  4279. files, as well as for I/O redirections within an `awk' program.  They
  4280. may not be used as source files with the `-f' option.
  4281.  
  4282.    Recognition of these special file names is disabled if `gawk' is in
  4283. compatibility mode (*note Command Line Options: Options.).
  4284.  
  4285.    *Caution*:  Unless your system actually has a `/dev/fd' directory
  4286. (or any of the other above listed special files), the interpretation of
  4287. these file names is done by `gawk' itself.  For example, using
  4288. `/dev/fd/4' for output will actually write on file descriptor 4, and
  4289. not on a new file descriptor that was `dup''ed from file descriptor 4.
  4290. Most of the time this does not matter; however, it is important to
  4291. *not* close any of the files related to file descriptors 0, 1, and 2.
  4292. If you do close one of these files, unpredictable behavior will result.
  4293.  
  4294.    The special files that provide process-related information may
  4295. disappear in a future version of `gawk'.  *Note Probable Future
  4296. Extensions: Future Extensions.
  4297.  
  4298. 
  4299. File: gawk.info,  Node: Close Files And Pipes,  Prev: Special Files,  Up: Printing
  4300.  
  4301. Closing Input and Output Files and Pipes
  4302. ========================================
  4303.  
  4304.    If the same file name or the same shell command is used with
  4305. `getline' (*note Explicit Input with `getline': Getline.) more than
  4306. once during the execution of an `awk' program, the file is opened (or
  4307. the command is executed) only the first time.  At that time, the first
  4308. record of input is read from that file or command.  The next time the
  4309. same file or command is used in `getline', another record is read from
  4310. it, and so on.
  4311.  
  4312.    Similarly, when a file or pipe is opened for output, the file name
  4313. or command associated with it is remembered by `awk' and subsequent
  4314. writes to the same file or command are appended to the previous writes.
  4315. The file or pipe stays open until `awk' exits.
  4316.  
  4317.    This implies that if you want to start reading the same file again
  4318. from the beginning, or if you want to rerun a shell command (rather than
  4319. reading more output from the command), you must take special steps.
  4320. What you must do is use the `close' function, as follows:
  4321.  
  4322.      close(FILENAME)
  4323.  
  4324. or
  4325.  
  4326.      close(COMMAND)
  4327.  
  4328.    The argument FILENAME or COMMAND can be any expression.  Its value
  4329. must *exactly* match the string that was used to open the file or start
  4330. the command (spaces and other "irrelevant" characters included). For
  4331. example, if you open a pipe with this:
  4332.  
  4333.      "sort -r names" | getline foo
  4334.  
  4335. then you must close it with this:
  4336.  
  4337.      close("sort -r names")
  4338.  
  4339.    Once this function call is executed, the next `getline' from that
  4340. file or command, or the next `print' or `printf' to that file or
  4341. command, will reopen the file or rerun the command.
  4342.  
  4343.    Because the expression that you use to close a file or pipeline must
  4344. exactly match the expression used to open the file or run the command,
  4345. it is good practice to use a variable to store the file name or command.
  4346. The previous example would become
  4347.  
  4348.      sortcom = "sort -r names"
  4349.      sortcom | getline foo
  4350.      ...
  4351.      close(sortcom)
  4352.  
  4353. This helps avoid hard-to-find typographical errors in your `awk'
  4354. programs.
  4355.  
  4356.    Here are some reasons why you might need to close an output file:
  4357.  
  4358.    * To write a file and read it back later on in the same `awk'
  4359.      program.  Close the file when you are finished writing it; then
  4360.      you can start reading it with `getline'.
  4361.  
  4362.    * To write numerous files, successively, in the same `awk' program.
  4363.      If you don't close the files, eventually you may exceed a system
  4364.      limit on the number of open files in one process.  So close each
  4365.      one when you are finished writing it.
  4366.  
  4367.    * To make a command finish.  When you redirect output through a pipe,
  4368.      the command reading the pipe normally continues to try to read
  4369.      input as long as the pipe is open.  Often this means the command
  4370.      cannot really do its work until the pipe is closed.  For example,
  4371.      if you redirect output to the `mail' program, the message is not
  4372.      actually sent until the pipe is closed.
  4373.  
  4374.    * To run the same program a second time, with the same arguments.
  4375.      This is not the same thing as giving more input to the first run!
  4376.  
  4377.      For example, suppose you pipe output to the `mail' program.  If you
  4378.      output several lines redirected to this pipe without closing it,
  4379.      they make a single message of several lines.  By contrast, if you
  4380.      close the pipe after each line of output, then each line makes a
  4381.      separate message.
  4382.  
  4383.    `close' returns a value of zero if the close succeeded.  Otherwise,
  4384. the value will be non-zero.  In this case, `gawk' sets the variable
  4385. `ERRNO' to a string describing the error that occurred.
  4386.  
  4387.    If you use more files than the system allows you to have open,
  4388. `gawk' will attempt to multiplex the available open files among your
  4389. data files.  `gawk''s ability to do this depends upon the facilities of
  4390. your operating system: it may not always work.  It is therefore both
  4391. good practice and good portability advice to always use `close' on your
  4392. files when you are done with them.
  4393.  
  4394. 
  4395. File: gawk.info,  Node: Expressions,  Next: Patterns and Actions,  Prev: Printing,  Up: Top
  4396.  
  4397. Expressions
  4398. ***********
  4399.  
  4400.    Expressions are the basic building blocks of `awk' patterns and
  4401. actions.  An expression evaluates to a value, which you can print, test,
  4402. store in a variable or pass to a function.  Additionally, an expression
  4403. can assign a new value to a variable or a field, with an assignment
  4404. operator.
  4405.  
  4406.    An expression can serve as a pattern or action statement on its own.
  4407. Most other kinds of statements contain one or more expressions which
  4408. specify data on which to operate.  As in other languages, expressions
  4409. in `awk' include variables, array references, constants, and function
  4410. calls, as well as combinations of these with various operators.
  4411.  
  4412. * Menu:
  4413.  
  4414. * Constants::                   String, numeric, and regexp constants.
  4415. * Using Constant Regexps::      When and how to use a regexp constant.
  4416. * Variables::                   Variables give names to values for later use.
  4417. * Conversion::                  The conversion of strings to numbers and vice
  4418.                                 versa.
  4419. * Arithmetic Ops::              Arithmetic operations (`+', `-',
  4420.                                 etc.)
  4421. * Concatenation::               Concatenating strings.
  4422. * Assignment Ops::              Changing the value of a variable or a field.
  4423. * Increment Ops::               Incrementing the numeric value of a variable.
  4424. * Truth Values::                What is "true" and what is "false".
  4425. * Typing and Comparison::       How variables acquire types, and how this
  4426.                                 affects comparison of numbers and strings with
  4427.                                 `<', etc.
  4428. * Boolean Ops::                 Combining comparison expressions using boolean
  4429.                                 operators `||' ("or"), `&&'
  4430.                                 ("and") and `!' ("not").
  4431. * Conditional Exp::             Conditional expressions select between two
  4432.                                 subexpressions under control of a third
  4433.                                 subexpression.
  4434. * Function Calls::              A function call is an expression.
  4435. * Precedence::                  How various operators nest.
  4436.  
  4437. 
  4438. File: gawk.info,  Node: Constants,  Next: Using Constant Regexps,  Prev: Expressions,  Up: Expressions
  4439.  
  4440. Constant Expressions
  4441. ====================
  4442.  
  4443.    The simplest type of expression is the "constant", which always has
  4444. the same value.  There are three types of constants: numeric constants,
  4445. string constants, and regular expression constants.
  4446.  
  4447. * Menu:
  4448.  
  4449. * Scalar Constants::            Numeric and string constants.
  4450. * Regexp Constants::            Regular Expression constants.
  4451.  
  4452. 
  4453. File: gawk.info,  Node: Scalar Constants,  Next: Regexp Constants,  Prev: Constants,  Up: Constants
  4454.  
  4455. Numeric and String Constants
  4456. ----------------------------
  4457.  
  4458.    A "numeric constant" stands for a number.  This number can be an
  4459. integer, a decimal fraction, or a number in scientific (exponential)
  4460. notation.(1) Here are some examples of numeric constants, which all
  4461. have the same value:
  4462.  
  4463.      105
  4464.      1.05e+2
  4465.      1050e-1
  4466.  
  4467.    A string constant consists of a sequence of characters enclosed in
  4468. double-quote marks.  For example:
  4469.  
  4470.      "parrot"
  4471.  
  4472. represents the string whose contents are `parrot'.  Strings in `gawk'
  4473. can be of any length and they can contain any of the possible eight-bit
  4474. ASCII characters including ASCII NUL (character code zero).  Other `awk'
  4475. implementations may have difficulty with some character codes.
  4476.  
  4477.    ---------- Footnotes ----------
  4478.  
  4479.    (1)  The internal representation uses double-precision floating
  4480. point numbers. If you don't know what that means, then don't worry
  4481. about it.
  4482.  
  4483. 
  4484. File: gawk.info,  Node: Regexp Constants,  Prev: Scalar Constants,  Up: Constants
  4485.  
  4486. Regular Expression Constants
  4487. ----------------------------
  4488.  
  4489.    A regexp constant is a regular expression description enclosed in
  4490. slashes, such as `/^beginning and end$/'.  Most regexps used in `awk'
  4491. programs are constant, but the `~' and `!~' matching operators can also
  4492. match computed or "dynamic" regexps (which are just ordinary strings or
  4493. variables that contain a regexp).
  4494.  
  4495. 
  4496. File: gawk.info,  Node: Using Constant Regexps,  Next: Variables,  Prev: Constants,  Up: Expressions
  4497.  
  4498. Using Regular Expression Constants
  4499. ==================================
  4500.  
  4501.    When used on the right hand side of the `~' or `!~' operators, a
  4502. regexp constant merely stands for the regexp that is to be matched.
  4503.  
  4504.    Regexp constants (such as `/foo/') may be used like simple
  4505. expressions.  When a regexp constant appears by itself, it has the same
  4506. meaning as if it appeared in a pattern, i.e. `($0 ~ /foo/)' (d.c.)
  4507. (*note Expressions as Patterns: Expression Patterns.).  This means that
  4508. the two code segments,
  4509.  
  4510.      if ($0 ~ /barfly/ || $0 ~ /camelot/)
  4511.          print "found"
  4512.  
  4513. and
  4514.  
  4515.      if (/barfly/ || /camelot/)
  4516.          print "found"
  4517.  
  4518. are exactly equivalent.
  4519.  
  4520.    One rather bizarre consequence of this rule is that the following
  4521. boolean expression is valid, but does not do what the user probably
  4522. intended:
  4523.  
  4524.      # note that /foo/ is on the left of the ~
  4525.      if (/foo/ ~ $1) print "found foo"
  4526.  
  4527. This code is "obviously" testing `$1' for a match against the regexp
  4528. `/foo/'.  But in fact, the expression `/foo/ ~ $1' actually means `($0
  4529. ~ /foo/) ~ $1'.  In other words, first match the input record against
  4530. the regexp `/foo/'.  The result will be either zero or one, depending
  4531. upon the success or failure of the match.  Then match that result
  4532. against the first field in the record.
  4533.  
  4534.    Since it is unlikely that you would ever really wish to make this
  4535. kind of test, `gawk' will issue a warning when it sees this construct in
  4536. a program.
  4537.  
  4538.    Another consequence of this rule is that the assignment statement
  4539.  
  4540.      matches = /foo/
  4541.  
  4542. will assign either zero or one to the variable `matches', depending
  4543. upon the contents of the current input record.
  4544.  
  4545.    This feature of the language was never well documented until the
  4546. POSIX specification.
  4547.  
  4548.    Constant regular expressions are also used as the first argument for
  4549. the `gensub', `sub' and `gsub' functions, and as the second argument of
  4550. the `match' function (*note Built-in Functions for String Manipulation:
  4551. String Functions.).  Modern implementations of `awk', including `gawk',
  4552. allow the third argument of `split' to be a regexp constant, while some
  4553. older implementations do not (d.c.).
  4554.  
  4555.    This can lead to confusion when attempting to use regexp constants
  4556. as arguments to user defined functions (*note User-defined Functions:
  4557. User-defined.).  For example:
  4558.  
  4559.      function mysub(pat, repl, str, global)
  4560.      {
  4561.          if (global)
  4562.              gsub(pat, repl, str)
  4563.          else
  4564.              sub(pat, repl, str)
  4565.          return str
  4566.      }
  4567.      
  4568.      {
  4569.          ...
  4570.          text = "hi! hi yourself!"
  4571.          mysub(/hi/, "howdy", text, 1)
  4572.          ...
  4573.      }
  4574.  
  4575.    In this example, the programmer wishes to pass a regexp constant to
  4576. the user-defined function `mysub', which will in turn pass it on to
  4577. either `sub' or `gsub'.  However, what really happens is that the `pat'
  4578. parameter will be either one or zero, depending upon whether or not
  4579. `$0' matches `/hi/'.
  4580.  
  4581.    As it is unlikely that you would ever really wish to pass a truth
  4582. value in this way, `gawk' will issue a warning when it sees a regexp
  4583. constant used as a parameter to a user-defined function.
  4584.  
  4585. 
  4586. File: gawk.info,  Node: Variables,  Next: Conversion,  Prev: Using Constant Regexps,  Up: Expressions
  4587.  
  4588. Variables
  4589. =========
  4590.  
  4591.    Variables are ways of storing values at one point in your program for
  4592. use later in another part of your program.  You can manipulate them
  4593. entirely within your program text, and you can also assign values to
  4594. them on the `awk' command line.
  4595.  
  4596. * Menu:
  4597.  
  4598. * Using Variables::             Using variables in your programs.
  4599. * Assignment Options::          Setting variables on the command line and a
  4600.                                 summary of command line syntax. This is an
  4601.                                 advanced method of input.
  4602.  
  4603. 
  4604. File: gawk.info,  Node: Using Variables,  Next: Assignment Options,  Prev: Variables,  Up: Variables
  4605.  
  4606. Using Variables in a Program
  4607. ----------------------------
  4608.  
  4609.    Variables let you give names to values and refer to them later.  You
  4610. have already seen variables in many of the examples.  The name of a
  4611. variable must be a sequence of letters, digits and underscores, but it
  4612. may not begin with a digit.  Case is significant in variable names; `a'
  4613. and `A' are distinct variables.
  4614.  
  4615.    A variable name is a valid expression by itself; it represents the
  4616. variable's current value.  Variables are given new values with
  4617. "assignment operators", "increment operators" and "decrement operators".
  4618. *Note Assignment Expressions: Assignment Ops.
  4619.  
  4620.    A few variables have special built-in meanings, such as `FS', the
  4621. field separator, and `NF', the number of fields in the current input
  4622. record.  *Note Built-in Variables::, for a list of them.  These
  4623. built-in variables can be used and assigned just like all other
  4624. variables, but their values are also used or changed automatically by
  4625. `awk'.  All built-in variables names are entirely upper-case.
  4626.  
  4627.    Variables in `awk' can be assigned either numeric or string values.
  4628. By default, variables are initialized to the empty string, which is
  4629. zero if converted to a number.  There is no need to "initialize" each
  4630. variable explicitly in `awk', the way you would in C and in most other
  4631. traditional languages.
  4632.  
  4633. 
  4634. File: gawk.info,  Node: Assignment Options,  Prev: Using Variables,  Up: Variables
  4635.  
  4636. Assigning Variables on the Command Line
  4637. ---------------------------------------
  4638.  
  4639.    You can set any `awk' variable by including a "variable assignment"
  4640. among the arguments on the command line when you invoke `awk' (*note
  4641. Other Command Line Arguments: Other Arguments.).  Such an assignment has
  4642. this form:
  4643.  
  4644.      VARIABLE=TEXT
  4645.  
  4646. With it, you can set a variable either at the beginning of the `awk'
  4647. run or in between input files.
  4648.  
  4649.    If you precede the assignment with the `-v' option, like this:
  4650.  
  4651.      -v VARIABLE=TEXT
  4652.  
  4653. then the variable is set at the very beginning, before even the `BEGIN'
  4654. rules are run.  The `-v' option and its assignment must precede all the
  4655. file name arguments, as well as the program text.  (*Note Command Line
  4656. Options: Options, for more information about the `-v' option.)
  4657.  
  4658.    Otherwise, the variable assignment is performed at a time determined
  4659. by its position among the input file arguments: after the processing of
  4660. the preceding input file argument.  For example:
  4661.  
  4662.      awk '{ print $n }' n=4 inventory-shipped n=2 BBS-list
  4663.  
  4664. prints the value of field number `n' for all input records.  Before the
  4665. first file is read, the command line sets the variable `n' equal to
  4666. four.  This causes the fourth field to be printed in lines from the
  4667. file `inventory-shipped'.  After the first file has finished, but
  4668. before the second file is started, `n' is set to two, so that the
  4669. second field is printed in lines from `BBS-list'.
  4670.  
  4671.      $ awk '{ print $n }' n=4 inventory-shipped n=2 BBS-list
  4672.      -| 15
  4673.      -| 24
  4674.      ...
  4675.      -| 555-5553
  4676.      -| 555-3412
  4677.      ...
  4678.  
  4679.    Command line arguments are made available for explicit examination by
  4680. the `awk' program in an array named `ARGV' (*note Using `ARGC' and
  4681. `ARGV': ARGC and ARGV.).
  4682.  
  4683.    `awk' processes the values of command line assignments for escape
  4684. sequences (d.c.) (*note Escape Sequences::.).
  4685.  
  4686. 
  4687. File: gawk.info,  Node: Conversion,  Next: Arithmetic Ops,  Prev: Variables,  Up: Expressions
  4688.  
  4689. Conversion of Strings and Numbers
  4690. =================================
  4691.  
  4692.    Strings are converted to numbers, and numbers to strings, if the
  4693. context of the `awk' program demands it.  For example, if the value of
  4694. either `foo' or `bar' in the expression `foo + bar' happens to be a
  4695. string, it is converted to a number before the addition is performed.
  4696. If numeric values appear in string concatenation, they are converted to
  4697. strings.  Consider this:
  4698.  
  4699.      two = 2; three = 3
  4700.      print (two three) + 4
  4701.  
  4702. This prints the (numeric) value 27.  The numeric values of the
  4703. variables `two' and `three' are converted to strings and concatenated
  4704. together, and the resulting string is converted back to the number 23,
  4705. to which four is then added.
  4706.  
  4707.    If, for some reason, you need to force a number to be converted to a
  4708. string, concatenate the empty string, `""', with that number.  To force
  4709. a string to be converted to a number, add zero to that string.
  4710.  
  4711.    A string is converted to a number by interpreting any numeric prefix
  4712. of the string as numerals: `"2.5"' converts to 2.5, `"1e3"' converts to
  4713. 1000, and `"25fix"' has a numeric value of 25.  Strings that can't be
  4714. interpreted as valid numbers are converted to zero.
  4715.  
  4716.    The exact manner in which numbers are converted into strings is
  4717. controlled by the `awk' built-in variable `CONVFMT' (*note Built-in
  4718. Variables::.).  Numbers are converted using the `sprintf' function
  4719. (*note Built-in Functions for String Manipulation: String Functions.)
  4720. with `CONVFMT' as the format specifier.
  4721.  
  4722.    `CONVFMT''s default value is `"%.6g"', which prints a value with at
  4723. least six significant digits.  For some applications you will want to
  4724. change it to specify more precision.  Double precision on most modern
  4725. machines gives you 16 or 17 decimal digits of precision.
  4726.  
  4727.    Strange results can happen if you set `CONVFMT' to a string that
  4728. doesn't tell `sprintf' how to format floating point numbers in a useful
  4729. way.  For example, if you forget the `%' in the format, all numbers
  4730. will be converted to the same constant string.
  4731.  
  4732.    As a special case, if a number is an integer, then the result of
  4733. converting it to a string is *always* an integer, no matter what the
  4734. value of `CONVFMT' may be.  Given the following code fragment:
  4735.  
  4736.      CONVFMT = "%2.2f"
  4737.      a = 12
  4738.      b = a ""
  4739.  
  4740. `b' has the value `"12"', not `"12.00"' (d.c.).
  4741.  
  4742.    Prior to the POSIX standard, `awk' specified that the value of
  4743. `OFMT' was used for converting numbers to strings.  `OFMT' specifies
  4744. the output format to use when printing numbers with `print'.  `CONVFMT'
  4745. was introduced in order to separate the semantics of conversion from
  4746. the semantics of printing.  Both `CONVFMT' and `OFMT' have the same
  4747. default value: `"%.6g"'.  In the vast majority of cases, old `awk'
  4748. programs will not change their behavior.  However, this use of `OFMT'
  4749. is something to keep in mind if you must port your program to other
  4750. implementations of `awk'; we recommend that instead of changing your
  4751. programs, you just port `gawk' itself!  *Note The `print' Statement:
  4752. Print, for more information on the `print' statement.
  4753.  
  4754. 
  4755. File: gawk.info,  Node: Arithmetic Ops,  Next: Concatenation,  Prev: Conversion,  Up: Expressions
  4756.  
  4757. Arithmetic Operators
  4758. ====================
  4759.  
  4760.    The `awk' language uses the common arithmetic operators when
  4761. evaluating expressions.  All of these arithmetic operators follow normal
  4762. precedence rules, and work as you would expect them to.
  4763.  
  4764.    Here is a file `grades' containing a list of student names and three
  4765. test scores per student (it's a small class):
  4766.  
  4767.      Pat   100 97 58
  4768.      Sandy  84 72 93
  4769.      Chris  72 92 89
  4770.  
  4771. This programs takes the file `grades', and prints the average of the
  4772. scores.
  4773.  
  4774.      $ awk '{ sum = $2 + $3 + $4 ; avg = sum / 3
  4775.      >        print $1, avg }' grades
  4776.      -| Pat 85
  4777.      -| Sandy 83
  4778.      -| Chris 84.3333
  4779.  
  4780.    This table lists the arithmetic operators in `awk', in order from
  4781. highest precedence to lowest:
  4782.  
  4783. `- X'
  4784.      Negation.
  4785.  
  4786. `+ X'
  4787.      Unary plus.  The expression is converted to a number.
  4788.  
  4789. `X ^ Y'
  4790. `X ** Y'
  4791.      Exponentiation: X raised to the Y power.  `2 ^ 3' has the value
  4792.      eight.  The character sequence `**' is equivalent to `^'.  (The
  4793.      POSIX standard only specifies the use of `^' for exponentiation.)
  4794.  
  4795. `X * Y'
  4796.      Multiplication.
  4797.  
  4798. `X / Y'
  4799.      Division.  Since all numbers in `awk' are real numbers, the result
  4800.      is not rounded to an integer: `3 / 4' has the value 0.75.
  4801.  
  4802. `X % Y'
  4803.      Remainder.  The quotient is rounded toward zero to an integer,
  4804.      multiplied by Y and this result is subtracted from X.  This
  4805.      operation is sometimes known as "trunc-mod."  The following
  4806.      relation always holds:
  4807.  
  4808.           b * int(a / b) + (a % b) == a
  4809.  
  4810.      One possibly undesirable effect of this definition of remainder is
  4811.      that `X % Y' is negative if X is negative.  Thus,
  4812.  
  4813.           -17 % 8 = -1
  4814.  
  4815.      In other `awk' implementations, the signedness of the remainder
  4816.      may be machine dependent.
  4817.  
  4818. `X + Y'
  4819.      Addition.
  4820.  
  4821. `X - Y'
  4822.      Subtraction.
  4823.  
  4824.    For maximum portability, do not use the `**' operator.
  4825.  
  4826.    Unary plus and minus have the same precedence, the multiplication
  4827. operators all have the same precedence, and addition and subtraction
  4828. have the same precedence.
  4829.  
  4830. 
  4831. File: gawk.info,  Node: Concatenation,  Next: Assignment Ops,  Prev: Arithmetic Ops,  Up: Expressions
  4832.  
  4833. String Concatenation
  4834. ====================
  4835.  
  4836.    There is only one string operation: concatenation.  It does not have
  4837. a specific operator to represent it.  Instead, concatenation is
  4838. performed by writing expressions next to one another, with no operator.
  4839. For example:
  4840.  
  4841.      $ awk '{ print "Field number one: " $1 }' BBS-list
  4842.      -| Field number one: aardvark
  4843.      -| Field number one: alpo-net
  4844.      ...
  4845.  
  4846.    Without the space in the string constant after the `:', the line
  4847. would run together.  For example:
  4848.  
  4849.      $ awk '{ print "Field number one:" $1 }' BBS-list
  4850.      -| Field number one:aardvark
  4851.      -| Field number one:alpo-net
  4852.      ...
  4853.  
  4854.    Since string concatenation does not have an explicit operator, it is
  4855. often necessary to insure that it happens where you want it to by using
  4856. parentheses to enclose the items to be concatenated.  For example, the
  4857. following code fragment does not concatenate `file' and `name' as you
  4858. might expect:
  4859.  
  4860.      file = "file"
  4861.      name = "name"
  4862.      print "something meaningful" > file name
  4863.  
  4864. It is necessary to use the following:
  4865.  
  4866.      print "something meaningful" > (file name)
  4867.  
  4868.    We recommend that you use parentheses around concatenation in all
  4869. but the most common contexts (such as on the right-hand side of `=').
  4870.  
  4871. 
  4872. File: gawk.info,  Node: Assignment Ops,  Next: Increment Ops,  Prev: Concatenation,  Up: Expressions
  4873.  
  4874. Assignment Expressions
  4875. ======================
  4876.  
  4877.    An "assignment" is an expression that stores a new value into a
  4878. variable.  For example, let's assign the value one to the variable `z':
  4879.  
  4880.      z = 1
  4881.  
  4882.    After this expression is executed, the variable `z' has the value
  4883. one.  Whatever old value `z' had before the assignment is forgotten.
  4884.  
  4885.    Assignments can store string values also.  For example, this would
  4886. store the value `"this food is good"' in the variable `message':
  4887.  
  4888.      thing = "food"
  4889.      predicate = "good"
  4890.      message = "this " thing " is " predicate
  4891.  
  4892. (This also illustrates string concatenation.)
  4893.  
  4894.    The `=' sign is called an "assignment operator".  It is the simplest
  4895. assignment operator because the value of the right-hand operand is
  4896. stored unchanged.
  4897.  
  4898.    Most operators (addition, concatenation, and so on) have no effect
  4899. except to compute a value.  If you ignore the value, you might as well
  4900. not use the operator.  An assignment operator is different; it does
  4901. produce a value, but even if you ignore the value, the assignment still
  4902. makes itself felt through the alteration of the variable.  We call this
  4903. a "side effect".
  4904.  
  4905.    The left-hand operand of an assignment need not be a variable (*note
  4906. Variables::.); it can also be a field (*note Changing the Contents of a
  4907. Field: Changing Fields.) or an array element (*note Arrays in `awk':
  4908. Arrays.).  These are all called "lvalues", which means they can appear
  4909. on the left-hand side of an assignment operator.  The right-hand
  4910. operand may be any expression; it produces the new value which the
  4911. assignment stores in the specified variable, field or array element.
  4912. (Such values are called "rvalues").
  4913.  
  4914.    It is important to note that variables do *not* have permanent types.
  4915. The type of a variable is simply the type of whatever value it happens
  4916. to hold at the moment.  In the following program fragment, the variable
  4917. `foo' has a numeric value at first, and a string value later on:
  4918.  
  4919.      foo = 1
  4920.      print foo
  4921.      foo = "bar"
  4922.      print foo
  4923.  
  4924. When the second assignment gives `foo' a string value, the fact that it
  4925. previously had a numeric value is forgotten.
  4926.  
  4927.    String values that do not begin with a digit have a numeric value of
  4928. zero. After executing this code, the value of `foo' is five:
  4929.  
  4930.      foo = "a string"
  4931.      foo = foo + 5
  4932.  
  4933. (Note that using a variable as a number and then later as a string can
  4934. be confusing and is poor programming style.  The above examples
  4935. illustrate how `awk' works, *not* how you should write your own
  4936. programs!)
  4937.  
  4938.    An assignment is an expression, so it has a value: the same value
  4939. that is assigned.  Thus, `z = 1' as an expression has the value one.
  4940. One consequence of this is that you can write multiple assignments
  4941. together:
  4942.  
  4943.      x = y = z = 0
  4944.  
  4945. stores the value zero in all three variables.  It does this because the
  4946. value of `z = 0', which is zero, is stored into `y', and then the value
  4947. of `y = z = 0', which is zero, is stored into `x'.
  4948.  
  4949.    You can use an assignment anywhere an expression is called for.  For
  4950. example, it is valid to write `x != (y = 1)' to set `y' to one and then
  4951. test whether `x' equals one.  But this style tends to make programs
  4952. hard to read; except in a one-shot program, you should not use such
  4953. nesting of assignments.
  4954.  
  4955.    Aside from `=', there are several other assignment operators that do
  4956. arithmetic with the old value of the variable.  For example, the
  4957. operator `+=' computes a new value by adding the right-hand value to
  4958. the old value of the variable.  Thus, the following assignment adds
  4959. five to the value of `foo':
  4960.  
  4961.      foo += 5
  4962.  
  4963. This is equivalent to the following:
  4964.  
  4965.      foo = foo + 5
  4966.  
  4967. Use whichever one makes the meaning of your program clearer.
  4968.  
  4969.    There are situations where using `+=' (or any assignment operator)
  4970. is *not* the same as simply repeating the left-hand operand in the
  4971. right-hand expression.  For example:
  4972.  
  4973.      # Thanks to Pat Rankin for this example
  4974.      BEGIN  {
  4975.          foo[rand()] += 5
  4976.          for (x in foo)
  4977.             print x, foo[x]
  4978.      
  4979.          bar[rand()] = bar[rand()] + 5
  4980.          for (x in bar)
  4981.             print x, bar[x]
  4982.      }
  4983.  
  4984. The indices of `bar' are guaranteed to be different, because `rand'
  4985. will return different values each time it is called.  (Arrays and the
  4986. `rand' function haven't been covered yet.  *Note Arrays in `awk':
  4987. Arrays, and see *Note Numeric Built-in Functions: Numeric Functions,
  4988. for more information).  This example illustrates an important fact
  4989. about the assignment operators: the left-hand expression is only
  4990. evaluated *once*.
  4991.  
  4992.    It is also up to the implementation as to which expression is
  4993. evaluated first, the left-hand one or the right-hand one.  Consider
  4994. this example:
  4995.  
  4996.      i = 1
  4997.      a[i += 2] = i + 1
  4998.  
  4999. The value of `a[3]' could be either two or four.
  5000.  
  5001.    Here is a table of the arithmetic assignment operators.  In each
  5002. case, the right-hand operand is an expression whose value is converted
  5003. to a number.
  5004.  
  5005. `LVALUE += INCREMENT'
  5006.      Adds INCREMENT to the value of LVALUE to make the new value of
  5007.      LVALUE.
  5008.  
  5009. `LVALUE -= DECREMENT'
  5010.      Subtracts DECREMENT from the value of LVALUE.
  5011.  
  5012. `LVALUE *= COEFFICIENT'
  5013.      Multiplies the value of LVALUE by COEFFICIENT.
  5014.  
  5015. `LVALUE /= DIVISOR'
  5016.      Divides the value of LVALUE by DIVISOR.
  5017.  
  5018. `LVALUE %= MODULUS'
  5019.      Sets LVALUE to its remainder by MODULUS.
  5020.  
  5021. `LVALUE ^= POWER'
  5022. `LVALUE **= POWER'
  5023.      Raises LVALUE to the power POWER.  (Only the `^=' operator is
  5024.      specified by POSIX.)
  5025.  
  5026.    For maximum portability, do not use the `**=' operator.
  5027.  
  5028. 
  5029. File: gawk.info,  Node: Increment Ops,  Next: Truth Values,  Prev: Assignment Ops,  Up: Expressions
  5030.  
  5031. Increment and Decrement Operators
  5032. =================================
  5033.  
  5034.    "Increment" and "decrement operators" increase or decrease the value
  5035. of a variable by one.  You could do the same thing with an assignment
  5036. operator, so the increment operators add no power to the `awk'
  5037. language; but they are convenient abbreviations for very common
  5038. operations.
  5039.  
  5040.    The operator to add one is written `++'.  It can be used to increment
  5041. a variable either before or after taking its value.
  5042.  
  5043.    To pre-increment a variable V, write `++V'.  This adds one to the
  5044. value of V and that new value is also the value of this expression.
  5045. The assignment expression `V += 1' is completely equivalent.
  5046.  
  5047.    Writing the `++' after the variable specifies post-increment.  This
  5048. increments the variable value just the same; the difference is that the
  5049. value of the increment expression itself is the variable's *old* value.
  5050. Thus, if `foo' has the value four, then the expression `foo++' has the
  5051. value four, but it changes the value of `foo' to five.
  5052.  
  5053.    The post-increment `foo++' is nearly equivalent to writing `(foo +=
  5054. 1) - 1'.  It is not perfectly equivalent because all numbers in `awk'
  5055. are floating point: in floating point, `foo + 1 - 1' does not
  5056. necessarily equal `foo'.  But the difference is minute as long as you
  5057. stick to numbers that are fairly small (less than 10e12).
  5058.  
  5059.    Any lvalue can be incremented.  Fields and array elements are
  5060. incremented just like variables.  (Use `$(i++)' when you wish to do a
  5061. field reference and a variable increment at the same time.  The
  5062. parentheses are necessary because of the precedence of the field
  5063. reference operator, `$'.)
  5064.  
  5065.    The decrement operator `--' works just like `++' except that it
  5066. subtracts one instead of adding.  Like `++', it can be used before the
  5067. lvalue to pre-decrement or after it to post-decrement.
  5068.  
  5069.    Here is a summary of increment and decrement expressions.
  5070.  
  5071. `++LVALUE'
  5072.      This expression increments LVALUE and the new value becomes the
  5073.      value of the expression.
  5074.  
  5075. `LVALUE++'
  5076.      This expression increments LVALUE, but the value of the expression
  5077.      is the *old* value of LVALUE.
  5078.  
  5079. `--LVALUE'
  5080.      Like `++LVALUE', but instead of adding, it subtracts.  It
  5081.      decrements LVALUE and delivers the value that results.
  5082.  
  5083. `LVALUE--'
  5084.      Like `LVALUE++', but instead of adding, it subtracts.  It
  5085.      decrements LVALUE.  The value of the expression is the *old* value
  5086.      of LVALUE.
  5087.  
  5088. 
  5089. File: gawk.info,  Node: Truth Values,  Next: Typing and Comparison,  Prev: Increment Ops,  Up: Expressions
  5090.  
  5091. True and False in `awk'
  5092. =======================
  5093.  
  5094.    Many programming languages have a special representation for the
  5095. concepts of "true" and "false."  Such languages usually use the special
  5096. constants `true' and `false', or perhaps their upper-case equivalents.
  5097.  
  5098.    `awk' is different.  It borrows a very simple concept of true and
  5099. false from C.  In `awk', any non-zero numeric value, *or* any non-empty
  5100. string value is true.  Any other value (zero or the null string, `""')
  5101. is false.  The following program will print `A strange truth value'
  5102. three times:
  5103.  
  5104.      BEGIN {
  5105.         if (3.1415927)
  5106.             print "A strange truth value"
  5107.         if ("Four Score And Seven Years Ago")
  5108.             print "A strange truth value"
  5109.         if (j = 57)
  5110.             print "A strange truth value"
  5111.      }
  5112.  
  5113.    There is a surprising consequence of the "non-zero or non-null" rule:
  5114. The string constant `"0"' is actually true, since it is non-null (d.c.).
  5115.  
  5116. 
  5117. File: gawk.info,  Node: Typing and Comparison,  Next: Boolean Ops,  Prev: Truth Values,  Up: Expressions
  5118.  
  5119. Variable Typing and Comparison Expressions
  5120. ==========================================
  5121.  
  5122.    Unlike other programming languages, `awk' variables do not have a
  5123. fixed type. Instead, they can be either a number or a string, depending
  5124. upon the value that is assigned to them.
  5125.  
  5126.    The 1992 POSIX standard introduced the concept of a "numeric
  5127. string", which is simply a string that looks like a number, for
  5128. example, `" +2"'.  This concept is used for determining the type of a
  5129. variable.
  5130.  
  5131.    The type of the variable is important, since the types of two
  5132. variables determine how they are compared.
  5133.  
  5134.    In `gawk', variable typing follows these rules.
  5135.  
  5136.   1. A numeric literal or the result of a numeric operation has the
  5137.      NUMERIC attribute.
  5138.  
  5139.   2. A string literal or the result of a string operation has the STRING
  5140.      attribute.
  5141.  
  5142.   3. Fields, `getline' input, `FILENAME', `ARGV' elements, `ENVIRON'
  5143.      elements and the elements of an array created by `split' that are
  5144.      numeric strings have the STRNUM attribute.  Otherwise, they have
  5145.      the STRING attribute.  Uninitialized variables also have the
  5146.      STRNUM attribute.
  5147.  
  5148.   4. Attributes propagate across assignments, but are not changed by
  5149.      any use.
  5150.  
  5151.    The last rule is particularly important. In the following program,
  5152. `a' has numeric type, even though it is later used in a string
  5153. operation.
  5154.  
  5155.      BEGIN {
  5156.               a = 12.345
  5157.               b = a " is a cute number"
  5158.               print b
  5159.      }
  5160.  
  5161.    When two operands are compared, either string comparison or numeric
  5162. comparison may be used, depending on the attributes of the operands,
  5163. according to the following, symmetric, matrix:
  5164.  
  5165.          +----------------------------------------------
  5166.          |    STRING        NUMERIC        STRNUM
  5167.      --------+----------------------------------------------
  5168.          |
  5169.      STRING    |    string        string        string
  5170.          |
  5171.      NUMERIC    |    string        numeric        numeric
  5172.          |
  5173.      STRNUM    |    string        numeric        numeric
  5174.      --------+----------------------------------------------
  5175.  
  5176.    The basic idea is that user input that looks numeric, and *only*
  5177. user input, should be treated as numeric, even though it is actually
  5178. made of characters, and is therefore also a string.
  5179.  
  5180.    "Comparison expressions" compare strings or numbers for
  5181. relationships such as equality.  They are written using "relational
  5182. operators", which are a superset of those in C.  Here is a table of
  5183. them:
  5184.  
  5185. `X < Y'
  5186.      True if X is less than Y.
  5187.  
  5188. `X <= Y'
  5189.      True if X is less than or equal to Y.
  5190.  
  5191. `X > Y'
  5192.      True if X is greater than Y.
  5193.  
  5194. `X >= Y'
  5195.      True if X is greater than or equal to Y.
  5196.  
  5197. `X == Y'
  5198.      True if X is equal to Y.
  5199.  
  5200. `X != Y'
  5201.      True if X is not equal to Y.
  5202.  
  5203. `X ~ Y'
  5204.      True if the string X matches the regexp denoted by Y.
  5205.  
  5206. `X !~ Y'
  5207.      True if the string X does not match the regexp denoted by Y.
  5208.  
  5209. `SUBSCRIPT in ARRAY'
  5210.      True if the array ARRAY has an element with the subscript
  5211.      SUBSCRIPT.
  5212.  
  5213.    Comparison expressions have the value one if true and zero if false.
  5214.  
  5215.    When comparing operands of mixed types, numeric operands are
  5216. converted to strings using the value of `CONVFMT' (*note Conversion of
  5217. Strings and Numbers: Conversion.).
  5218.  
  5219.    Strings are compared by comparing the first character of each, then
  5220. the second character of each, and so on.  Thus `"10"' is less than
  5221. `"9"'.  If there are two strings where one is a prefix of the other,
  5222. the shorter string is less than the longer one.  Thus `"abc"' is less
  5223. than `"abcd"'.
  5224.  
  5225.    It is very easy to accidentally mistype the `==' operator, and leave
  5226. off one of the `='s.  The result is still valid `awk' code, but the
  5227. program will not do what you mean:
  5228.  
  5229.      if (a = b)   # oops! should be a == b
  5230.         ...
  5231.      else
  5232.         ...
  5233.  
  5234. Unless `b' happens to be zero or the null string, the `if' part of the
  5235. test will always succeed.  Because the operators are so similar, this
  5236. kind of error is very difficult to spot when scanning the source code.
  5237.  
  5238.    Here are some sample expressions, how `gawk' compares them, and what
  5239. the result of the comparison is.
  5240.  
  5241. `1.5 <= 2.0'
  5242.      numeric comparison (true)
  5243.  
  5244. `"abc" >= "xyz"'
  5245.      string comparison (false)
  5246.  
  5247. `1.5 != " +2"'
  5248.      string comparison (true)
  5249.  
  5250. `"1e2" < "3"'
  5251.      string comparison (true)
  5252.  
  5253. `a = 2; b = "2"'
  5254. `a == b'
  5255.      string comparison (true)
  5256.  
  5257. `a = 2; b = " +2"'
  5258. `a == b'
  5259.      string comparison (false)
  5260.  
  5261.    In this example,
  5262.  
  5263.      $ echo 1e2 3 | awk '{ print ($1 < $2) ? "true" : "false" }'
  5264.      -| false
  5265.  
  5266. the result is `false' since both `$1' and `$2' are numeric strings and
  5267. thus both have the STRNUM attribute, dictating a numeric comparison.
  5268.  
  5269.    The purpose of the comparison rules and the use of numeric strings is
  5270. to attempt to produce the behavior that is "least surprising," while
  5271. still "doing the right thing."
  5272.  
  5273.    String comparisons and regular expression comparisons are very
  5274. different.  For example,
  5275.  
  5276.      x == "foo"
  5277.  
  5278. has the value of one, or is true, if the variable `x' is precisely
  5279. `foo'.  By contrast,
  5280.  
  5281.      x ~ /foo/
  5282.  
  5283. has the value one if `x' contains `foo', such as `"Oh, what a fool am
  5284. I!"'.
  5285.  
  5286.    The right hand operand of the `~' and `!~' operators may be either a
  5287. regexp constant (`/.../'), or an ordinary expression, in which case the
  5288. value of the expression as a string is used as a dynamic regexp (*note
  5289. How to Use Regular Expressions: Regexp Usage.; also *note Using Dynamic
  5290. Regexps: Computed Regexps.).
  5291.  
  5292.    In recent implementations of `awk', a constant regular expression in
  5293. slashes by itself is also an expression.  The regexp `/REGEXP/' is an
  5294. abbreviation for this comparison expression:
  5295.  
  5296.      $0 ~ /REGEXP/
  5297.  
  5298.    One special place where `/foo/' is *not* an abbreviation for `$0 ~
  5299. /foo/' is when it is the right-hand operand of `~' or `!~'!  *Note
  5300. Using Regular Expression Constants: Using Constant Regexps, where this
  5301. is discussed in more detail.
  5302.  
  5303. 
  5304. File: gawk.info,  Node: Boolean Ops,  Next: Conditional Exp,  Prev: Typing and Comparison,  Up: Expressions
  5305.  
  5306. Boolean Expressions
  5307. ===================
  5308.  
  5309.    A "boolean expression" is a combination of comparison expressions or
  5310. matching expressions, using the boolean operators "or" (`||'), "and"
  5311. (`&&'), and "not" (`!'), along with parentheses to control nesting.
  5312. The truth value of the boolean expression is computed by combining the
  5313. truth values of the component expressions.  Boolean expressions are
  5314. also referred to as "logical expressions".  The terms are equivalent.
  5315.  
  5316.    Boolean expressions can be used wherever comparison and matching
  5317. expressions can be used.  They can be used in `if', `while', `do' and
  5318. `for' statements (*note Control Statements in Actions: Statements.).
  5319. They have numeric values (one if true, zero if false), which come into
  5320. play if the result of the boolean expression is stored in a variable, or
  5321. used in arithmetic.
  5322.  
  5323.    In addition, every boolean expression is also a valid pattern, so
  5324. you can use one as a pattern to control the execution of rules.
  5325.  
  5326.    Here are descriptions of the three boolean operators, with examples.
  5327.  
  5328. `BOOLEAN1 && BOOLEAN2'
  5329.      True if both BOOLEAN1 and BOOLEAN2 are true.  For example, the
  5330.      following statement prints the current input record if it contains
  5331.      both `2400' and `foo'.
  5332.  
  5333.           if ($0 ~ /2400/ && $0 ~ /foo/) print
  5334.  
  5335.      The subexpression BOOLEAN2 is evaluated only if BOOLEAN1 is true.
  5336.      This can make a difference when BOOLEAN2 contains expressions that
  5337.      have side effects: in the case of `$0 ~ /foo/ && ($2 == bar++)',
  5338.      the variable `bar' is not incremented if there is no `foo' in the
  5339.      record.
  5340.  
  5341. `BOOLEAN1 || BOOLEAN2'
  5342.      True if at least one of BOOLEAN1 or BOOLEAN2 is true.  For
  5343.      example, the following statement prints all records in the input
  5344.      that contain *either* `2400' or `foo', or both.
  5345.  
  5346.           if ($0 ~ /2400/ || $0 ~ /foo/) print
  5347.  
  5348.      The subexpression BOOLEAN2 is evaluated only if BOOLEAN1 is false.
  5349.      This can make a difference when BOOLEAN2 contains expressions
  5350.      that have side effects.
  5351.  
  5352. `! BOOLEAN'
  5353.      True if BOOLEAN is false.  For example, the following program
  5354.      prints all records in the input file `BBS-list' that do *not*
  5355.      contain the string `foo'.
  5356.  
  5357.           awk '{ if (! ($0 ~ /foo/)) print }' BBS-list
  5358.  
  5359.    The `&&' and `||' operators are called "short-circuit" operators
  5360. because of the way they work.  Evaluation of the full expression is
  5361. "short-circuited" if the result can be determined part way through its
  5362. evaluation.
  5363.  
  5364.    You can continue a statement that uses `&&' or `||' simply by
  5365. putting a newline after them.  But you cannot put a newline in front of
  5366. either of these operators without using backslash continuation (*note
  5367. `awk' Statements Versus Lines: Statements/Lines.).
  5368.  
  5369.    The actual value of an expression using the `!' operator will be
  5370. either one or zero, depending upon the truth value of the expression it
  5371. is applied to.
  5372.  
  5373.    The `!' operator is often useful for changing the sense of a flag
  5374. variable from false to true and back again. For example, the following
  5375. program is one way to print lines in between special bracketing lines:
  5376.  
  5377.      $1 == "START"   { interested = ! interested }
  5378.      interested == 1 { print }
  5379.      $1 == "END"     { interested = ! interested }
  5380.  
  5381. The variable `interested', like all `awk' variables, starts out
  5382. initialized to zero, which is also false.  When a line is seen whose
  5383. first field is `START', the value of `interested' is toggled to true,
  5384. using `!'. The next rule prints lines as long as `interested' is true.
  5385. When a line is seen whose first field is `END', `interested' is toggled
  5386. back to false.
  5387.  
  5388. 
  5389. File: gawk.info,  Node: Conditional Exp,  Next: Function Calls,  Prev: Boolean Ops,  Up: Expressions
  5390.  
  5391. Conditional Expressions
  5392. =======================
  5393.  
  5394.    A "conditional expression" is a special kind of expression with
  5395. three operands.  It allows you to use one expression's value to select
  5396. one of two other expressions.
  5397.  
  5398.    The conditional expression is the same as in the C language:
  5399.  
  5400.      SELECTOR ? IF-TRUE-EXP : IF-FALSE-EXP
  5401.  
  5402. There are three subexpressions.  The first, SELECTOR, is always
  5403. computed first.  If it is "true" (not zero and not null) then
  5404. IF-TRUE-EXP is computed next and its value becomes the value of the
  5405. whole expression.  Otherwise, IF-FALSE-EXP is computed next and its
  5406. value becomes the value of the whole expression.
  5407.  
  5408.    For example, this expression produces the absolute value of `x':
  5409.  
  5410.      x > 0 ? x : -x
  5411.  
  5412.    Each time the conditional expression is computed, exactly one of
  5413. IF-TRUE-EXP and IF-FALSE-EXP is computed; the other is ignored.  This
  5414. is important when the expressions contain side effects.  For example,
  5415. this conditional expression examines element `i' of either array `a' or
  5416. array `b', and increments `i'.
  5417.  
  5418.      x == y ? a[i++] : b[i++]
  5419.  
  5420. This is guaranteed to increment `i' exactly once, because each time
  5421. only one of the two increment expressions is executed, and the other is
  5422. not.  *Note Arrays in `awk': Arrays, for more information about arrays.
  5423.  
  5424.    As a minor `gawk' extension, you can continue a statement that uses
  5425. `?:' simply by putting a newline after either character.  However, you
  5426. cannot put a newline in front of either character without using
  5427. backslash continuation (*note `awk' Statements Versus Lines:
  5428. Statements/Lines.).
  5429.  
  5430. 
  5431. File: gawk.info,  Node: Function Calls,  Next: Precedence,  Prev: Conditional Exp,  Up: Expressions
  5432.  
  5433. Function Calls
  5434. ==============
  5435.  
  5436.    A "function" is a name for a particular calculation.  Because it has
  5437. a name, you can ask for it by name at any point in the program.  For
  5438. example, the function `sqrt' computes the square root of a number.
  5439.  
  5440.    A fixed set of functions are "built-in", which means they are
  5441. available in every `awk' program.  The `sqrt' function is one of these.
  5442. *Note Built-in Functions: Built-in, for a list of built-in functions
  5443. and their descriptions.  In addition, you can define your own functions
  5444. for use in your program.  *Note User-defined Functions: User-defined,
  5445. for how to do this.
  5446.  
  5447.    The way to use a function is with a "function call" expression,
  5448. which consists of the function name followed immediately by a list of
  5449. "arguments" in parentheses.  The arguments are expressions which
  5450. provide the raw materials for the function's calculations.  When there
  5451. is more than one argument, they are separated by commas.  If there are
  5452. no arguments, write just `()' after the function name.  Here are some
  5453. examples:
  5454.  
  5455.      sqrt(x^2 + y^2)        one argument
  5456.      atan2(y, x)            two arguments
  5457.      rand()                 no arguments
  5458.  
  5459.    *Do not put any space between the function name and the
  5460. open-parenthesis!*  A user-defined function name looks just like the
  5461. name of a variable, and space would make the expression look like
  5462. concatenation of a variable with an expression inside parentheses.
  5463. Space before the parenthesis is harmless with built-in functions, but
  5464. it is best not to get into the habit of using space to avoid mistakes
  5465. with user-defined functions.
  5466.  
  5467.    Each function expects a particular number of arguments.  For
  5468. example, the `sqrt' function must be called with a single argument, the
  5469. number to take the square root of:
  5470.  
  5471.      sqrt(ARGUMENT)
  5472.  
  5473.    Some of the built-in functions allow you to omit the final argument.
  5474. If you do so, they use a reasonable default.  *Note Built-in Functions:
  5475. Built-in, for full details.  If arguments are omitted in calls to
  5476. user-defined functions, then those arguments are treated as local
  5477. variables, initialized to the empty string (*note User-defined
  5478. Functions: User-defined.).
  5479.  
  5480.    Like every other expression, the function call has a value, which is
  5481. computed by the function based on the arguments you give it.  In this
  5482. example, the value of `sqrt(ARGUMENT)' is the square root of ARGUMENT.
  5483. A function can also have side effects, such as assigning values to
  5484. certain variables or doing I/O.
  5485.  
  5486.    Here is a command to read numbers, one number per line, and print the
  5487. square root of each one:
  5488.  
  5489.      $ awk '{ print "The square root of", $1, "is", sqrt($1) }'
  5490.      1
  5491.      -| The square root of 1 is 1
  5492.      3
  5493.      -| The square root of 3 is 1.73205
  5494.      5
  5495.      -| The square root of 5 is 2.23607
  5496.      `Control-d'
  5497.  
  5498. 
  5499. File: gawk.info,  Node: Precedence,  Prev: Function Calls,  Up: Expressions
  5500.  
  5501. Operator Precedence (How Operators Nest)
  5502. ========================================
  5503.  
  5504.    "Operator precedence" determines how operators are grouped, when
  5505. different operators appear close by in one expression.  For example,
  5506. `*' has higher precedence than `+'; thus, `a + b * c' means to multiply
  5507. `b' and `c', and then add `a' to the product (i.e. `a + (b * c)').
  5508.  
  5509.    You can overrule the precedence of the operators by using
  5510. parentheses.  You can think of the precedence rules as saying where the
  5511. parentheses are assumed to be if you do not write parentheses yourself.
  5512. In fact, it is wise to always use parentheses whenever you have an
  5513. unusual combination of operators, because other people who read the
  5514. program may not remember what the precedence is in this case.  You
  5515. might forget, too; then you could make a mistake.  Explicit parentheses
  5516. will help prevent any such mistake.
  5517.  
  5518.    When operators of equal precedence are used together, the leftmost
  5519. operator groups first, except for the assignment, conditional and
  5520. exponentiation operators, which group in the opposite order.  Thus, `a
  5521. - b + c' groups as `(a - b) + c', and `a = b = c' groups as `a = (b =
  5522. c)'.
  5523.  
  5524.    The precedence of prefix unary operators does not matter as long as
  5525. only unary operators are involved, because there is only one way to
  5526. interpret them--innermost first.  Thus, `$++i' means `$(++i)' and
  5527. `++$x' means `++($x)'.  However, when another operator follows the
  5528. operand, then the precedence of the unary operators can matter.  Thus,
  5529. `$x^2' means `($x)^2', but `-x^2' means `-(x^2)', because `-' has lower
  5530. precedence than `^' while `$' has higher precedence.
  5531.  
  5532.    Here is a table of `awk''s operators, in order from highest
  5533. precedence to lowest:
  5534.  
  5535. `(...)'
  5536.      Grouping.
  5537.  
  5538. `$'
  5539.      Field.
  5540.  
  5541. `++ --'
  5542.      Increment, decrement.
  5543.  
  5544. `^ **'
  5545.      Exponentiation.  These operators group right-to-left.  (The `**'
  5546.      operator is not specified by POSIX.)
  5547.  
  5548. `+ - !'
  5549.      Unary plus, minus, logical "not".
  5550.  
  5551. `* / %'
  5552.      Multiplication, division, modulus.
  5553.  
  5554. `+ -'
  5555.      Addition, subtraction.
  5556.  
  5557. `Concatenation'
  5558.      No special token is used to indicate concatenation.  The operands
  5559.      are simply written side by side.
  5560.  
  5561. `< <= == !='
  5562. `> >= >> |'
  5563.      Relational, and redirection.  The relational operators and the
  5564.      redirections have the same precedence level.  Characters such as
  5565.      `>' serve both as relationals and as redirections; the context
  5566.      distinguishes between the two meanings.
  5567.  
  5568.      Note that the I/O redirection operators in `print' and `printf'
  5569.      statements belong to the statement level, not to expressions.  The
  5570.      redirection does not produce an expression which could be the
  5571.      operand of another operator.  As a result, it does not make sense
  5572.      to use a redirection operator near another operator of lower
  5573.      precedence, without parentheses.  Such combinations, for example
  5574.      `print foo > a ? b : c', result in syntax errors.  The correct way
  5575.      to write this statement is `print foo > (a ? b : c)'.
  5576.  
  5577. `~ !~'
  5578.      Matching, non-matching.
  5579.  
  5580. `in'
  5581.      Array membership.
  5582.  
  5583. `&&'
  5584.      Logical "and".
  5585.  
  5586. `||'
  5587.      Logical "or".
  5588.  
  5589. `?:'
  5590.      Conditional.  This operator groups right-to-left.
  5591.  
  5592. `= += -= *='
  5593. `/= %= ^= **='
  5594.      Assignment.  These operators group right-to-left.  (The `**='
  5595.      operator is not specified by POSIX.)
  5596.  
  5597. 
  5598. File: gawk.info,  Node: Patterns and Actions,  Next: Statements,  Prev: Expressions,  Up: Top
  5599.  
  5600. Patterns and Actions
  5601. ********************
  5602.  
  5603.    As you have already seen, each `awk' statement consists of a pattern
  5604. with an associated action.  This chapter describes how you build
  5605. patterns and actions.
  5606.  
  5607. * Menu:
  5608.  
  5609. * Pattern Overview::            What goes into a pattern.
  5610. * Action Overview::             What goes into an action.
  5611.  
  5612. 
  5613. File: gawk.info,  Node: Pattern Overview,  Next: Action Overview,  Prev: Patterns and Actions,  Up: Patterns and Actions
  5614.  
  5615. Pattern Elements
  5616. ================
  5617.  
  5618.    Patterns in `awk' control the execution of rules: a rule is executed
  5619. when its pattern matches the current input record.  This section
  5620. explains all about how to write patterns.
  5621.  
  5622. * Menu:
  5623.  
  5624. * Kinds of Patterns::           A list of all kinds of patterns.
  5625. * Regexp Patterns::             Using regexps as patterns.
  5626. * Expression Patterns::         Any expression can be used as a pattern.
  5627. * Ranges::                      Pairs of patterns specify record ranges.
  5628. * BEGIN/END::                   Specifying initialization and cleanup rules.
  5629. * Empty::                       The empty pattern, which matches every record.
  5630.  
  5631. 
  5632. File: gawk.info,  Node: Kinds of Patterns,  Next: Regexp Patterns,  Prev: Pattern Overview,  Up: Pattern Overview
  5633.  
  5634. Kinds of Patterns
  5635. -----------------
  5636.  
  5637.    Here is a summary of the types of patterns supported in `awk'.
  5638.  
  5639. `/REGULAR EXPRESSION/'
  5640.      A regular expression as a pattern.  It matches when the text of the
  5641.      input record fits the regular expression.  (*Note Regular
  5642.      Expressions: Regexp.)
  5643.  
  5644. `EXPRESSION'
  5645.      A single expression.  It matches when its value is non-zero (if a
  5646.      number) or non-null (if a string).  (*Note Expressions as
  5647.      Patterns: Expression Patterns.)
  5648.  
  5649. `PAT1, PAT2'
  5650.      A pair of patterns separated by a comma, specifying a range of
  5651.      records.  The range includes both the initial record that matches
  5652.      PAT1, and the final record that matches PAT2.  (*Note Specifying
  5653.      Record Ranges with Patterns: Ranges.)
  5654.  
  5655. `BEGIN'
  5656. `END'
  5657.      Special patterns for you to supply start-up or clean-up actions
  5658.      for your `awk' program.  (*Note The `BEGIN' and `END' Special
  5659.      Patterns: BEGIN/END.)
  5660.  
  5661. `EMPTY'
  5662.      The empty pattern matches every input record.  (*Note The Empty
  5663.      Pattern: Empty.)
  5664.  
  5665. 
  5666. File: gawk.info,  Node: Regexp Patterns,  Next: Expression Patterns,  Prev: Kinds of Patterns,  Up: Pattern Overview
  5667.  
  5668. Regular Expressions as Patterns
  5669. -------------------------------
  5670.  
  5671.    We have been using regular expressions as patterns since our early
  5672. examples.  This kind of pattern is simply a regexp constant in the
  5673. pattern part of a rule.  Its  meaning is `$0 ~ /PATTERN/'.  The pattern
  5674. matches when the input record matches the regexp.  For example:
  5675.  
  5676.      /foo|bar|baz/  { buzzwords++ }
  5677.      END            { print buzzwords, "buzzwords seen" }
  5678.  
  5679. 
  5680. File: gawk.info,  Node: Expression Patterns,  Next: Ranges,  Prev: Regexp Patterns,  Up: Pattern Overview
  5681.  
  5682. Expressions as Patterns
  5683. -----------------------
  5684.  
  5685.    Any `awk' expression is valid as an `awk' pattern.  Then the pattern
  5686. matches if the expression's value is non-zero (if a number) or non-null
  5687. (if a string).
  5688.  
  5689.    The expression is reevaluated each time the rule is tested against a
  5690. new input record.  If the expression uses fields such as `$1', the
  5691. value depends directly on the new input record's text; otherwise, it
  5692. depends only on what has happened so far in the execution of the `awk'
  5693. program, but that may still be useful.
  5694.  
  5695.    A very common kind of expression used as a pattern is the comparison
  5696. expression, using the comparison operators described in *Note Variable
  5697. Typing and Comparison Expressions: Typing and Comparison.
  5698.  
  5699.    Regexp matching and non-matching are also very common expressions.
  5700. The left operand of the `~' and `!~' operators is a string.  The right
  5701. operand is either a constant regular expression enclosed in slashes
  5702. (`/REGEXP/'), or any expression, whose string value is used as a
  5703. dynamic regular expression (*note Using Dynamic Regexps: Computed
  5704. Regexps.).
  5705.  
  5706.    The following example prints the second field of each input record
  5707. whose first field is precisely `foo'.
  5708.  
  5709.      $ awk '$1 == "foo" { print $2 }' BBS-list
  5710.  
  5711. (There is no output, since there is no BBS site named "foo".) Contrast
  5712. this with the following regular expression match, which would accept
  5713. any record with a first field that contains `foo':
  5714.  
  5715.      $ awk '$1 ~ /foo/ { print $2 }' BBS-list
  5716.      -| 555-1234
  5717.      -| 555-6699
  5718.      -| 555-6480
  5719.      -| 555-2127
  5720.  
  5721.    Boolean expressions are also commonly used as patterns.  Whether the
  5722. pattern matches an input record depends on whether its subexpressions
  5723. match.
  5724.  
  5725.    For example, the following command prints all records in `BBS-list'
  5726. that contain both `2400' and `foo'.
  5727.  
  5728.      $ awk '/2400/ && /foo/' BBS-list
  5729.      -| fooey        555-1234     2400/1200/300     B
  5730.  
  5731.    The following command prints all records in `BBS-list' that contain
  5732. *either* `2400' or `foo', or both.
  5733.  
  5734.      $ awk '/2400/ || /foo/' BBS-list
  5735.      -| alpo-net     555-3412     2400/1200/300     A
  5736.      -| bites        555-1675     2400/1200/300     A
  5737.      -| fooey        555-1234     2400/1200/300     B
  5738.      -| foot         555-6699     1200/300          B
  5739.      -| macfoo       555-6480     1200/300          A
  5740.      -| sdace        555-3430     2400/1200/300     A
  5741.      -| sabafoo      555-2127     1200/300          C
  5742.  
  5743.    The following command prints all records in `BBS-list' that do *not*
  5744. contain the string `foo'.
  5745.  
  5746.      $ awk '! /foo/' BBS-list
  5747.      -| aardvark     555-5553     1200/300          B
  5748.      -| alpo-net     555-3412     2400/1200/300     A
  5749.      -| barfly       555-7685     1200/300          A
  5750.      -| bites        555-1675     2400/1200/300     A
  5751.      -| camelot      555-0542     300               C
  5752.      -| core         555-2912     1200/300          C
  5753.      -| sdace        555-3430     2400/1200/300     A
  5754.  
  5755.    The subexpressions of a boolean operator in a pattern can be
  5756. constant regular expressions, comparisons, or any other `awk'
  5757. expressions.  Range patterns are not expressions, so they cannot appear
  5758. inside boolean patterns.  Likewise, the special patterns `BEGIN' and
  5759. `END', which never match any input record, are not expressions and
  5760. cannot appear inside boolean patterns.
  5761.  
  5762.    A regexp constant as a pattern is also a special case of an
  5763. expression pattern.  `/foo/' as an expression has the value one if `foo'
  5764. appears in the current input record; thus, as a pattern, `/foo/'
  5765. matches any record containing `foo'.
  5766.  
  5767. 
  5768. File: gawk.info,  Node: Ranges,  Next: BEGIN/END,  Prev: Expression Patterns,  Up: Pattern Overview
  5769.  
  5770. Specifying Record Ranges with Patterns
  5771. --------------------------------------
  5772.  
  5773.    A "range pattern" is made of two patterns separated by a comma, of
  5774. the form `BEGPAT, ENDPAT'.  It matches ranges of consecutive input
  5775. records.  The first pattern, BEGPAT, controls where the range begins,
  5776. and the second one, ENDPAT, controls where it ends.  For example,
  5777.  
  5778.      awk '$1 == "on", $1 == "off"'
  5779.  
  5780. prints every record between `on'/`off' pairs, inclusive.
  5781.  
  5782.    A range pattern starts out by matching BEGPAT against every input
  5783. record; when a record matches BEGPAT, the range pattern becomes "turned
  5784. on".  The range pattern matches this record.  As long as it stays
  5785. turned on, it automatically matches every input record read.  It also
  5786. matches ENDPAT against every input record; when that succeeds, the
  5787. range pattern is turned off again for the following record.  Then it
  5788. goes back to checking BEGPAT against each record.
  5789.  
  5790.    The record that turns on the range pattern and the one that turns it
  5791. off both match the range pattern.  If you don't want to operate on
  5792. these records, you can write `if' statements in the rule's action to
  5793. distinguish them from the records you are interested in.
  5794.  
  5795.    It is possible for a pattern to be turned both on and off by the same
  5796. record, if the record satisfies both conditions.  Then the action is
  5797. executed for just that record.
  5798.  
  5799.    For example, suppose you have text between two identical markers (say
  5800. the `%' symbol) that you wish to ignore.  You might try to combine a
  5801. range pattern that describes the delimited text with the `next'
  5802. statement (not discussed yet, *note The `next' Statement: Next
  5803. Statement.), which causes `awk' to skip any further processing of the
  5804. current record and start over again with the next input record. Such a
  5805. program would like this:
  5806.  
  5807.      /^%$/,/^%$/    { next }
  5808.                     { print }
  5809.  
  5810. This program fails because the range pattern is both turned on and
  5811. turned off by the first line with just a `%' on it.  To accomplish this
  5812. task, you must write the program this way, using a flag:
  5813.  
  5814.      /^%$/     { skip = ! skip; next }
  5815.      skip == 1 { next } # skip lines with `skip' set
  5816.  
  5817.    Note that in a range pattern, the `,' has the lowest precedence (is
  5818. evaluated last) of all the operators.  Thus, for example, the following
  5819. program attempts to combine a range pattern with another, simpler test.
  5820.  
  5821.      echo Yes | awk '/1/,/2/ || /Yes/'
  5822.  
  5823.    The author of this program intended it to mean `(/1/,/2/) || /Yes/'.
  5824. However, `awk' interprets this as `/1/, (/2/ || /Yes/)'.  This cannot
  5825. be changed or worked around; range patterns do not combine with other
  5826. patterns.
  5827.  
  5828. 
  5829. File: gawk.info,  Node: BEGIN/END,  Next: Empty,  Prev: Ranges,  Up: Pattern Overview
  5830.  
  5831. The `BEGIN' and `END' Special Patterns
  5832. --------------------------------------
  5833.  
  5834.    `BEGIN' and `END' are special patterns.  They are not used to match
  5835. input records.  Rather, they supply start-up or clean-up actions for
  5836. your `awk' script.
  5837.  
  5838. * Menu:
  5839.  
  5840. * Using BEGIN/END::             How and why to use BEGIN/END rules.
  5841. * I/O And BEGIN/END::           I/O issues in BEGIN/END rules.
  5842.  
  5843. 
  5844. File: gawk.info,  Node: Using BEGIN/END,  Next: I/O And BEGIN/END,  Prev: BEGIN/END,  Up: BEGIN/END
  5845.  
  5846. Startup and Cleanup Actions
  5847. ...........................
  5848.  
  5849.    A `BEGIN' rule is executed, once, before the first input record has
  5850. been read.  An `END' rule is executed, once, after all the input has
  5851. been read.  For example:
  5852.  
  5853.      $ awk '
  5854.      > BEGIN { print "Analysis of \"foo\"" }
  5855.      > /foo/ { ++n }
  5856.      > END   { print "\"foo\" appears " n " times." }' BBS-list
  5857.      -| Analysis of "foo"
  5858.      -| "foo" appears 4 times.
  5859.  
  5860.    This program finds the number of records in the input file `BBS-list'
  5861. that contain the string `foo'.  The `BEGIN' rule prints a title for the
  5862. report.  There is no need to use the `BEGIN' rule to initialize the
  5863. counter `n' to zero, as `awk' does this automatically (*note
  5864. Variables::.).
  5865.  
  5866.    The second rule increments the variable `n' every time a record
  5867. containing the pattern `foo' is read.  The `END' rule prints the value
  5868. of `n' at the end of the run.
  5869.  
  5870.    The special patterns `BEGIN' and `END' cannot be used in ranges or
  5871. with boolean operators (indeed, they cannot be used with any operators).
  5872.  
  5873.    An `awk' program may have multiple `BEGIN' and/or `END' rules.  They
  5874. are executed in the order they appear, all the `BEGIN' rules at
  5875. start-up and all the `END' rules at termination.  `BEGIN' and `END'
  5876. rules may be intermixed with other rules.  This feature was added in
  5877. the 1987 version of `awk', and is included in the POSIX standard.  The
  5878. original (1978) version of `awk' required you to put the `BEGIN' rule
  5879. at the beginning of the program, and the `END' rule at the end, and
  5880. only allowed one of each.  This is no longer required, but it is a good
  5881. idea in terms of program organization and readability.
  5882.  
  5883.    Multiple `BEGIN' and `END' rules are useful for writing library
  5884. functions, since each library file can have its own `BEGIN' and/or
  5885. `END' rule to do its own initialization and/or cleanup.  Note that the
  5886. order in which library functions are named on the command line controls
  5887. the order in which their `BEGIN' and `END' rules are executed.
  5888. Therefore you have to be careful to write such rules in library files
  5889. so that the order in which they are executed doesn't matter.  *Note
  5890. Command Line Options: Options, for more information on using library
  5891. functions.  *Note A Library of `awk' Functions: Library Functions, for
  5892. a number of useful library functions.
  5893.  
  5894.    If an `awk' program only has a `BEGIN' rule, and no other rules,
  5895. then the program exits after the `BEGIN' rule has been run.  (The
  5896. original version of `awk' used to keep reading and ignoring input until
  5897. end of file was seen.)  However, if an `END' rule exists, then the
  5898. input will be read, even if there are no other rules in the program.
  5899. This is necessary in case the `END' rule checks the `FNR' and `NR'
  5900. variables (d.c.).
  5901.  
  5902.    `BEGIN' and `END' rules must have actions; there is no default
  5903. action for these rules since there is no current record when they run.
  5904.  
  5905. 
  5906. File: gawk.info,  Node: I/O And BEGIN/END,  Prev: Using BEGIN/END,  Up: BEGIN/END
  5907.  
  5908. Input/Output from `BEGIN' and `END' Rules
  5909. .........................................
  5910.  
  5911.    There are several (sometimes subtle) issues involved when doing I/O
  5912. from a `BEGIN' or `END' rule.
  5913.  
  5914.    The first has to do with the value of `$0' in a `BEGIN' rule.  Since
  5915. `BEGIN' rules are executed before any input is read, there simply is no
  5916. input record, and therefore no fields, when executing `BEGIN' rules.
  5917. References to `$0' and the fields yield a null string or zero,
  5918. depending upon the context.  One way to give `$0' a real value is to
  5919. execute a `getline' command without a variable (*note Explicit Input
  5920. with `getline': Getline.).  Another way is to simply assign a value to
  5921. it.
  5922.  
  5923.    The second point is similar to the first, but from the other
  5924. direction.  Inside an `END' rule, what is the value of `$0' and `NF'?
  5925. Traditionally, due largely to implementation issues, `$0' and `NF' were
  5926. *undefined* inside an `END' rule.  The POSIX standard specified that
  5927. `NF' was available in an `END' rule, containing the number of fields
  5928. from the last input record.  Due most probably to an oversight, the
  5929. standard does not say that `$0' is also preserved, although logically
  5930. one would think that it should be.  In fact, `gawk' does preserve the
  5931. value of `$0' for use in `END' rules.  Be aware, however, that Unix
  5932. `awk', and possibly other implementations, do not.
  5933.  
  5934.    The third point follows from the first two.  What is the meaning of
  5935. `print' inside a `BEGIN' or `END' rule?  The meaning is the same as
  5936. always, `print $0'.  If `$0' is the null string, then this prints an
  5937. empty line.  Many long time `awk' programmers use `print' in `BEGIN'
  5938. and `END' rules, to mean `print ""', relying on `$0' being null.  While
  5939. you might generally get away with this in `BEGIN' rules, in `gawk' at
  5940. least, it is a very bad idea in `END' rules.  It is also poor style,
  5941. since if you want an empty line in the output, you should say so
  5942. explicitly in your program.
  5943.  
  5944. 
  5945. File: gawk.info,  Node: Empty,  Prev: BEGIN/END,  Up: Pattern Overview
  5946.  
  5947. The Empty Pattern
  5948. -----------------
  5949.  
  5950.    An empty (i.e. non-existent) pattern is considered to match *every*
  5951. input record.  For example, the program:
  5952.  
  5953.      awk '{ print $1 }' BBS-list
  5954.  
  5955. prints the first field of every record.
  5956.  
  5957. 
  5958. File: gawk.info,  Node: Action Overview,  Prev: Pattern Overview,  Up: Patterns and Actions
  5959.  
  5960. Overview of Actions
  5961. ===================
  5962.  
  5963.    An `awk' program or script consists of a series of rules and
  5964. function definitions, interspersed.  (Functions are described later.
  5965. *Note User-defined Functions: User-defined.)
  5966.  
  5967.    A rule contains a pattern and an action, either of which (but not
  5968. both) may be omitted.  The purpose of the "action" is to tell `awk'
  5969. what to do once a match for the pattern is found.  Thus, in outline, an
  5970. `awk' program generally looks like this:
  5971.  
  5972.      [PATTERN] [{ ACTION }]
  5973.      [PATTERN] [{ ACTION }]
  5974.      ...
  5975.      function NAME(ARGS) { ... }
  5976.      ...
  5977.  
  5978.    An action consists of one or more `awk' "statements", enclosed in
  5979. curly braces (`{' and `}').  Each statement specifies one thing to be
  5980. done.  The statements are separated by newlines or semicolons.
  5981.  
  5982.    The curly braces around an action must be used even if the action
  5983. contains only one statement, or even if it contains no statements at
  5984. all.  However, if you omit the action entirely, omit the curly braces as
  5985. well.  An omitted action is equivalent to `{ print $0 }'.
  5986.  
  5987.      /foo/  { }  # match foo, do nothing - empty action
  5988.      /foo/       # match foo, print the record - omitted action
  5989.  
  5990.    Here are the kinds of statements supported in `awk':
  5991.  
  5992.    * Expressions, which can call functions or assign values to variables
  5993.      (*note Expressions::.).  Executing this kind of statement simply
  5994.      computes the value of the expression.  This is useful when the
  5995.      expression has side effects (*note Assignment Expressions:
  5996.      Assignment Ops.).
  5997.  
  5998.    * Control statements, which specify the control flow of `awk'
  5999.      programs.  The `awk' language gives you C-like constructs (`if',
  6000.      `for', `while', and `do') as well as a few special ones (*note
  6001.      Control Statements in Actions: Statements.).
  6002.  
  6003.    * Compound statements, which consist of one or more statements
  6004.      enclosed in curly braces.  A compound statement is used in order
  6005.      to put several statements together in the body of an `if',
  6006.      `while', `do' or `for' statement.
  6007.  
  6008.    * Input statements, using the `getline' command (*note Explicit
  6009.      Input with `getline': Getline.), the `next' statement (*note The
  6010.      `next' Statement: Next Statement.), and the `nextfile' statement
  6011.      (*note The `nextfile' Statement: Nextfile Statement.).
  6012.  
  6013.    * Output statements, `print' and `printf'.  *Note Printing Output:
  6014.      Printing.
  6015.  
  6016.    * Deletion statements, for deleting array elements.  *Note The
  6017.      `delete' Statement: Delete.
  6018.  
  6019. 
  6020. File: gawk.info,  Node: Statements,  Next: Built-in Variables,  Prev: Patterns and Actions,  Up: Top
  6021.  
  6022. Control Statements in Actions
  6023. *****************************
  6024.  
  6025.    "Control statements" such as `if', `while', and so on control the
  6026. flow of execution in `awk' programs.  Most of the control statements in
  6027. `awk' are patterned on similar statements in C.
  6028.  
  6029.    All the control statements start with special keywords such as `if'
  6030. and `while', to distinguish them from simple expressions.
  6031.  
  6032.    Many control statements contain other statements; for example, the
  6033. `if' statement contains another statement which may or may not be
  6034. executed.  The contained statement is called the "body".  If you want
  6035. to include more than one statement in the body, group them into a
  6036. single "compound statement" with curly braces, separating them with
  6037. newlines or semicolons.
  6038.  
  6039. * Menu:
  6040.  
  6041. * If Statement::                Conditionally execute some `awk'
  6042.                                 statements.
  6043. * While Statement::             Loop until some condition is satisfied.
  6044. * Do Statement::                Do specified action while looping until some
  6045.                                 condition is satisfied.
  6046. * For Statement::               Another looping statement, that provides
  6047.                                 initialization and increment clauses.
  6048. * Break Statement::             Immediately exit the innermost enclosing loop.
  6049. * Continue Statement::          Skip to the end of the innermost enclosing
  6050.                                 loop.
  6051. * Next Statement::              Stop processing the current input record.
  6052. * Nextfile Statement::          Stop processing the current file.
  6053. * Exit Statement::              Stop execution of `awk'.
  6054.  
  6055. 
  6056. File: gawk.info,  Node: If Statement,  Next: While Statement,  Prev: Statements,  Up: Statements
  6057.  
  6058. The `if'-`else' Statement
  6059. =========================
  6060.  
  6061.    The `if'-`else' statement is `awk''s decision-making statement.  It
  6062. looks like this:
  6063.  
  6064.      if (CONDITION) THEN-BODY [else ELSE-BODY]
  6065.  
  6066. The CONDITION is an expression that controls what the rest of the
  6067. statement will do.  If CONDITION is true, THEN-BODY is executed;
  6068. otherwise, ELSE-BODY is executed.  The `else' part of the statement is
  6069. optional.  The condition is considered false if its value is zero or
  6070. the null string, and true otherwise.
  6071.  
  6072.    Here is an example:
  6073.  
  6074.      if (x % 2 == 0)
  6075.          print "x is even"
  6076.      else
  6077.          print "x is odd"
  6078.  
  6079.    In this example, if the expression `x % 2 == 0' is true (that is,
  6080. the value of `x' is evenly divisible by two), then the first `print'
  6081. statement is executed, otherwise the second `print' statement is
  6082. executed.
  6083.  
  6084.    If the `else' appears on the same line as THEN-BODY, and THEN-BODY
  6085. is not a compound statement (i.e. not surrounded by curly braces), then
  6086. a semicolon must separate THEN-BODY from `else'.  To illustrate this,
  6087. let's rewrite the previous example:
  6088.  
  6089.      if (x % 2 == 0) print "x is even"; else
  6090.              print "x is odd"
  6091.  
  6092. If you forget the `;', `awk' won't be able to interpret the statement,
  6093. and you will get a syntax error.
  6094.  
  6095.    We would not actually write this example this way, because a human
  6096. reader might fail to see the `else' if it were not the first thing on
  6097. its line.
  6098.  
  6099. 
  6100. File: gawk.info,  Node: While Statement,  Next: Do Statement,  Prev: If Statement,  Up: Statements
  6101.  
  6102. The `while' Statement
  6103. =====================
  6104.  
  6105.    In programming, a "loop" means a part of a program that can be
  6106. executed two or more times in succession.
  6107.  
  6108.    The `while' statement is the simplest looping statement in `awk'.
  6109. It repeatedly executes a statement as long as a condition is true.  It
  6110. looks like this:
  6111.  
  6112.      while (CONDITION)
  6113.        BODY
  6114.  
  6115. Here BODY is a statement that we call the "body" of the loop, and
  6116. CONDITION is an expression that controls how long the loop keeps
  6117. running.
  6118.  
  6119.    The first thing the `while' statement does is test CONDITION.  If
  6120. CONDITION is true, it executes the statement BODY.  (The CONDITION is
  6121. true when the value is not zero and not a null string.) After BODY has
  6122. been executed, CONDITION is tested again, and if it is still true, BODY
  6123. is executed again.  This process repeats until CONDITION is no longer
  6124. true.  If CONDITION is initially false, the body of the loop is never
  6125. executed, and `awk' continues with the statement following the loop.
  6126.  
  6127.    This example prints the first three fields of each record, one per
  6128. line.
  6129.  
  6130.      awk '{ i = 1
  6131.             while (i <= 3) {
  6132.                 print $i
  6133.                 i++
  6134.             }
  6135.      }' inventory-shipped
  6136.  
  6137. Here the body of the loop is a compound statement enclosed in braces,
  6138. containing two statements.
  6139.  
  6140.    The loop works like this: first, the value of `i' is set to one.
  6141. Then, the `while' tests whether `i' is less than or equal to three.
  6142. This is true when `i' equals one, so the `i'-th field is printed.  Then
  6143. the `i++' increments the value of `i' and the loop repeats.  The loop
  6144. terminates when `i' reaches four.
  6145.  
  6146.    As you can see, a newline is not required between the condition and
  6147. the body; but using one makes the program clearer unless the body is a
  6148. compound statement or is very simple.  The newline after the open-brace
  6149. that begins the compound statement is not required either, but the
  6150. program would be harder to read without it.
  6151.  
  6152. 
  6153. File: gawk.info,  Node: Do Statement,  Next: For Statement,  Prev: While Statement,  Up: Statements
  6154.  
  6155. The `do'-`while' Statement
  6156. ==========================
  6157.  
  6158.    The `do' loop is a variation of the `while' looping statement.  The
  6159. `do' loop executes the BODY once, and then repeats BODY as long as
  6160. CONDITION is true.  It looks like this:
  6161.  
  6162.      do
  6163.        BODY
  6164.      while (CONDITION)
  6165.  
  6166.    Even if CONDITION is false at the start, BODY is executed at least
  6167. once (and only once, unless executing BODY makes CONDITION true).
  6168. Contrast this with the corresponding `while' statement:
  6169.  
  6170.      while (CONDITION)
  6171.        BODY
  6172.  
  6173. This statement does not execute BODY even once if CONDITION is false to
  6174. begin with.
  6175.  
  6176.    Here is an example of a `do' statement:
  6177.  
  6178.      awk '{ i = 1
  6179.             do {
  6180.                print $0
  6181.                i++
  6182.             } while (i <= 10)
  6183.      }'
  6184.  
  6185. This program prints each input record ten times.  It isn't a very
  6186. realistic example, since in this case an ordinary `while' would do just
  6187. as well.  But this reflects actual experience; there is only
  6188. occasionally a real use for a `do' statement.
  6189.  
  6190. 
  6191. File: gawk.info,  Node: For Statement,  Next: Break Statement,  Prev: Do Statement,  Up: Statements
  6192.  
  6193. The `for' Statement
  6194. ===================
  6195.  
  6196.    The `for' statement makes it more convenient to count iterations of a
  6197. loop.  The general form of the `for' statement looks like this:
  6198.  
  6199.      for (INITIALIZATION; CONDITION; INCREMENT)
  6200.        BODY
  6201.  
  6202. The INITIALIZATION, CONDITION and INCREMENT parts are arbitrary `awk'
  6203. expressions, and BODY stands for any `awk' statement.
  6204.  
  6205.    The `for' statement starts by executing INITIALIZATION.  Then, as
  6206. long as CONDITION is true, it repeatedly executes BODY and then
  6207. INCREMENT.  Typically INITIALIZATION sets a variable to either zero or
  6208. one, INCREMENT adds one to it, and CONDITION compares it against the
  6209. desired number of iterations.
  6210.  
  6211.    Here is an example of a `for' statement:
  6212.  
  6213.      awk '{ for (i = 1; i <= 3; i++)
  6214.                print $i
  6215.      }' inventory-shipped
  6216.  
  6217. This prints the first three fields of each input record, one field per
  6218. line.
  6219.  
  6220.    You cannot set more than one variable in the INITIALIZATION part
  6221. unless you use a multiple assignment statement such as `x = y = 0',
  6222. which is possible only if all the initial values are equal.  (But you
  6223. can initialize additional variables by writing their assignments as
  6224. separate statements preceding the `for' loop.)
  6225.  
  6226.    The same is true of the INCREMENT part; to increment additional
  6227. variables, you must write separate statements at the end of the loop.
  6228. The C compound expression, using C's comma operator, would be useful in
  6229. this context, but it is not supported in `awk'.
  6230.  
  6231.    Most often, INCREMENT is an increment expression, as in the example
  6232. above.  But this is not required; it can be any expression whatever.
  6233. For example, this statement prints all the powers of two between one
  6234. and 100:
  6235.  
  6236.      for (i = 1; i <= 100; i *= 2)
  6237.        print i
  6238.  
  6239.    Any of the three expressions in the parentheses following the `for'
  6240. may be omitted if there is nothing to be done there.  Thus,
  6241. `for (; x > 0;)' is equivalent to `while (x > 0)'.  If the CONDITION is
  6242. omitted, it is treated as TRUE, effectively yielding an "infinite loop"
  6243. (i.e. a loop that will never terminate).
  6244.  
  6245.    In most cases, a `for' loop is an abbreviation for a `while' loop,
  6246. as shown here:
  6247.  
  6248.      INITIALIZATION
  6249.      while (CONDITION) {
  6250.        BODY
  6251.        INCREMENT
  6252.      }
  6253.  
  6254. The only exception is when the `continue' statement (*note The
  6255. `continue' Statement: Continue Statement.) is used inside the loop;
  6256. changing a `for' statement to a `while' statement in this way can
  6257. change the effect of the `continue' statement inside the loop.
  6258.  
  6259.    There is an alternate version of the `for' loop, for iterating over
  6260. all the indices of an array:
  6261.  
  6262.      for (i in array)
  6263.          DO SOMETHING WITH array[i]
  6264.  
  6265. *Note Scanning All Elements of an Array: Scanning an Array, for more
  6266. information on this version of the `for' loop.
  6267.  
  6268.    The `awk' language has a `for' statement in addition to a `while'
  6269. statement because often a `for' loop is both less work to type and more
  6270. natural to think of.  Counting the number of iterations is very common
  6271. in loops.  It can be easier to think of this counting as part of
  6272. looping rather than as something to do inside the loop.
  6273.  
  6274.    The next section has more complicated examples of `for' loops.
  6275.  
  6276. 
  6277. File: gawk.info,  Node: Break Statement,  Next: Continue Statement,  Prev: For Statement,  Up: Statements
  6278.  
  6279. The `break' Statement
  6280. =====================
  6281.  
  6282.    The `break' statement jumps out of the innermost `for', `while', or
  6283. `do' loop that encloses it.  The following example finds the smallest
  6284. divisor of any integer, and also identifies prime numbers:
  6285.  
  6286.      awk '# find smallest divisor of num
  6287.           { num = $1
  6288.             for (div = 2; div*div <= num; div++)
  6289.               if (num % div == 0)
  6290.                 break
  6291.             if (num % div == 0)
  6292.               printf "Smallest divisor of %d is %d\n", num, div
  6293.             else
  6294.               printf "%d is prime\n", num
  6295.           }'
  6296.  
  6297.    When the remainder is zero in the first `if' statement, `awk'
  6298. immediately "breaks out" of the containing `for' loop.  This means that
  6299. `awk' proceeds immediately to the statement following the loop and
  6300. continues processing.  (This is very different from the `exit'
  6301. statement which stops the entire `awk' program.  *Note The `exit'
  6302. Statement: Exit Statement.)
  6303.  
  6304.    Here is another program equivalent to the previous one.  It
  6305. illustrates how the CONDITION of a `for' or `while' could just as well
  6306. be replaced with a `break' inside an `if':
  6307.  
  6308.      awk '# find smallest divisor of num
  6309.           { num = $1
  6310.             for (div = 2; ; div++) {
  6311.               if (num % div == 0) {
  6312.                 printf "Smallest divisor of %d is %d\n", num, div
  6313.                 break
  6314.               }
  6315.               if (div*div > num) {
  6316.                 printf "%d is prime\n", num
  6317.                 break
  6318.               }
  6319.             }
  6320.      }'
  6321.  
  6322.    As described above, the `break' statement has no meaning when used
  6323. outside the body of a loop.  However, although it was never documented,
  6324. historical implementations of `awk' have treated the `break' statement
  6325. outside of a loop as if it were a `next' statement (*note The `next'
  6326. Statement: Next Statement.).  Recent versions of Unix `awk' no longer
  6327. allow this usage.  `gawk' will support this use of `break' only if
  6328. `--traditional' has been specified on the command line (*note Command
  6329. Line Options: Options.).  Otherwise, it will be treated as an error,
  6330. since the POSIX standard specifies that `break' should only be used
  6331. inside the body of a loop (d.c.).
  6332.  
  6333. 
  6334. File: gawk.info,  Node: Continue Statement,  Next: Next Statement,  Prev: Break Statement,  Up: Statements
  6335.  
  6336. The `continue' Statement
  6337. ========================
  6338.  
  6339.    The `continue' statement, like `break', is used only inside `for',
  6340. `while', and `do' loops.  It skips over the rest of the loop body,
  6341. causing the next cycle around the loop to begin immediately.  Contrast
  6342. this with `break', which jumps out of the loop altogether.
  6343.  
  6344.    The `continue' statement in a `for' loop directs `awk' to skip the
  6345. rest of the body of the loop, and resume execution with the
  6346. increment-expression of the `for' statement.  The following program
  6347. illustrates this fact:
  6348.  
  6349.      awk 'BEGIN {
  6350.           for (x = 0; x <= 20; x++) {
  6351.               if (x == 5)
  6352.                   continue
  6353.               printf "%d ", x
  6354.           }
  6355.           print ""
  6356.      }'
  6357.  
  6358. This program prints all the numbers from zero to 20, except for five,
  6359. for which the `printf' is skipped.  Since the increment `x++' is not
  6360. skipped, `x' does not remain stuck at five.  Contrast the `for' loop
  6361. above with this `while' loop:
  6362.  
  6363.      awk 'BEGIN {
  6364.           x = 0
  6365.           while (x <= 20) {
  6366.               if (x == 5)
  6367.                   continue
  6368.               printf "%d ", x
  6369.               x++
  6370.           }
  6371.           print ""
  6372.      }'
  6373.  
  6374. This program loops forever once `x' gets to five.
  6375.  
  6376.    As described above, the `continue' statement has no meaning when
  6377. used outside the body of a loop.  However, although it was never
  6378. documented, historical implementations of `awk' have treated the
  6379. `continue' statement outside of a loop as if it were a `next' statement
  6380. (*note The `next' Statement: Next Statement.).  Recent versions of Unix
  6381. `awk' no longer allow this usage.  `gawk' will support this use of
  6382. `continue' only if `--traditional' has been specified on the command
  6383. line (*note Command Line Options: Options.).  Otherwise, it will be
  6384. treated as an error, since the POSIX standard specifies that `continue'
  6385. should only be used inside the body of a loop (d.c.).
  6386.  
  6387. 
  6388. File: gawk.info,  Node: Next Statement,  Next: Nextfile Statement,  Prev: Continue Statement,  Up: Statements
  6389.  
  6390. The `next' Statement
  6391. ====================
  6392.  
  6393.    The `next' statement forces `awk' to immediately stop processing the
  6394. current record and go on to the next record.  This means that no
  6395. further rules are executed for the current record.  The rest of the
  6396. current rule's action is not executed either.
  6397.  
  6398.    Contrast this with the effect of the `getline' function (*note
  6399. Explicit Input with `getline': Getline.).  That too causes `awk' to
  6400. read the next record immediately, but it does not alter the flow of
  6401. control in any way.  So the rest of the current action executes with a
  6402. new input record.
  6403.  
  6404.    At the highest level, `awk' program execution is a loop that reads
  6405. an input record and then tests each rule's pattern against it.  If you
  6406. think of this loop as a `for' statement whose body contains the rules,
  6407. then the `next' statement is analogous to a `continue' statement: it
  6408. skips to the end of the body of this implicit loop, and executes the
  6409. increment (which reads another record).
  6410.  
  6411.    For example, if your `awk' program works only on records with four
  6412. fields, and you don't want it to fail when given bad input, you might
  6413. use this rule near the beginning of the program:
  6414.  
  6415.      NF != 4 {
  6416.        err = sprintf("%s:%d: skipped: NF != 4\n", FILENAME, FNR)
  6417.        print err > "/dev/stderr"
  6418.        next
  6419.      }
  6420.  
  6421. so that the following rules will not see the bad record.  The error
  6422. message is redirected to the standard error output stream, as error
  6423. messages should be.  *Note Special File Names in `gawk': Special Files.
  6424.  
  6425.    According to the POSIX standard, the behavior is undefined if the
  6426. `next' statement is used in a `BEGIN' or `END' rule.  `gawk' will treat
  6427. it as a syntax error.  Although POSIX permits it, some other `awk'
  6428. implementations don't allow the `next' statement inside function bodies
  6429. (*note User-defined Functions: User-defined.).  Just as any other
  6430. `next' statement, a `next' inside a function body reads the next record
  6431. and starts processing it with the first rule in the program.
  6432.  
  6433.    If the `next' statement causes the end of the input to be reached,
  6434. then the code in any `END' rules will be executed.  *Note The `BEGIN'
  6435. and `END' Special Patterns: BEGIN/END.
  6436.  
  6437. 
  6438. File: gawk.info,  Node: Nextfile Statement,  Next: Exit Statement,  Prev: Next Statement,  Up: Statements
  6439.  
  6440. The `nextfile' Statement
  6441. ========================
  6442.  
  6443.    `gawk' provides the `nextfile' statement, which is similar to the
  6444. `next' statement.  However, instead of abandoning processing of the
  6445. current record, the `nextfile' statement instructs `gawk' to stop
  6446. processing the current data file.
  6447.  
  6448.    Upon execution of the `nextfile' statement, `FILENAME' is updated to
  6449. the name of the next data file listed on the command line, `FNR' is
  6450. reset to one, `ARGIND' is incremented, and processing starts over with
  6451. the first rule in the progam.  *Note Built-in Variables::.
  6452.  
  6453.    If the `nextfile' statement causes the end of the input to be
  6454. reached, then the code in any `END' rules will be executed.  *Note The
  6455. `BEGIN' and `END' Special Patterns: BEGIN/END.
  6456.  
  6457.    The `nextfile' statement is a `gawk' extension; it is not
  6458. (currently) available in any other `awk' implementation.  *Note
  6459. Implementing `nextfile' as a Function: Nextfile Function, for a
  6460. user-defined function you can use to simulate the `nextfile' statement.
  6461.  
  6462.    The `nextfile' statement would be useful if you have many data files
  6463. to process, and you expect that you would not want to process every
  6464. record in every file.  Normally, in order to move on to the next data
  6465. file, you would have to continue scanning the unwanted records.  The
  6466. `nextfile' statement accomplishes this much more efficiently.
  6467.  
  6468.    *Caution:*  Versions of `gawk' prior to 3.0 used two words (`next
  6469. file') for the `nextfile' statement.  This was changed in 3.0 to one
  6470. word, since the treatment of `file' was inconsistent. When it appeared
  6471. after `next', it was a keyword.  Otherwise, it was a regular
  6472. identifier.  The old usage is still accepted. However, `gawk' will
  6473. generate a warning message, and support for `next file' will eventually
  6474. be discontinued in a future version of `gawk'.
  6475.  
  6476. 
  6477. File: gawk.info,  Node: Exit Statement,  Prev: Nextfile Statement,  Up: Statements
  6478.  
  6479. The `exit' Statement
  6480. ====================
  6481.  
  6482.    The `exit' statement causes `awk' to immediately stop executing the
  6483. current rule and to stop processing input; any remaining input is
  6484. ignored.  It looks like this:
  6485.  
  6486.      exit [RETURN CODE]
  6487.  
  6488.    If an `exit' statement is executed from a `BEGIN' rule the program
  6489. stops processing everything immediately.  No input records are read.
  6490. However, if an `END' rule is present, it is executed (*note The `BEGIN'
  6491. and `END' Special Patterns: BEGIN/END.).
  6492.  
  6493.    If `exit' is used as part of an `END' rule, it causes the program to
  6494. stop immediately.
  6495.  
  6496.    An `exit' statement that is not part of a `BEGIN' or `END' rule
  6497. stops the execution of any further automatic rules for the current
  6498. record, skips reading any remaining input records, and executes the
  6499. `END' rule if there is one.
  6500.  
  6501.    If you do not want the `END' rule to do its job in this case, you
  6502. can set a variable to non-zero before the `exit' statement, and check
  6503. that variable in the `END' rule.  *Note Assertions: Assert Function,
  6504. for an example that does this.
  6505.  
  6506.    If an argument is supplied to `exit', its value is used as the exit
  6507. status code for the `awk' process.  If no argument is supplied, `exit'
  6508. returns status zero (success).  In the case where an argument is
  6509. supplied to a first `exit' statement, and then `exit' is called a
  6510. second time with no argument, the previously supplied exit value is
  6511. used (d.c.).
  6512.  
  6513.    For example, let's say you've discovered an error condition you
  6514. really don't know how to handle.  Conventionally, programs report this
  6515. by exiting with a non-zero status.  Your `awk' program can do this
  6516. using an `exit' statement with a non-zero argument.  Here is an example:
  6517.  
  6518.      BEGIN {
  6519.             if (("date" | getline date_now) < 0) {
  6520.               print "Can't get system date" > "/dev/stderr"
  6521.               exit 1
  6522.             }
  6523.             print "current date is", date_now
  6524.             close("date")
  6525.      }
  6526.  
  6527. 
  6528. File: gawk.info,  Node: Built-in Variables,  Next: Arrays,  Prev: Statements,  Up: Top
  6529.  
  6530. Built-in Variables
  6531. ******************
  6532.  
  6533.    Most `awk' variables are available for you to use for your own
  6534. purposes; they never change except when your program assigns values to
  6535. them, and never affect anything except when your program examines them.
  6536. However, a few variables in `awk' have special built-in meanings.  Some
  6537. of them `awk' examines automatically, so that they enable you to tell
  6538. `awk' how to do certain things.  Others are set automatically by `awk',
  6539. so that they carry information from the internal workings of `awk' to
  6540. your program.
  6541.  
  6542.    This chapter documents all the built-in variables of `gawk'.  Most
  6543. of them are also documented in the chapters describing their areas of
  6544. activity.
  6545.  
  6546. * Menu:
  6547.  
  6548. * User-modified::               Built-in variables that you change to control
  6549.                                 `awk'.
  6550. * Auto-set::                    Built-in variables where `awk' gives you
  6551.                                 information.
  6552. * ARGC and ARGV::               Ways to use `ARGC' and `ARGV'.
  6553.  
  6554. 
  6555. File: gawk.info,  Node: User-modified,  Next: Auto-set,  Prev: Built-in Variables,  Up: Built-in Variables
  6556.  
  6557. Built-in Variables that Control `awk'
  6558. =====================================
  6559.  
  6560.    This is an alphabetical list of the variables which you can change to
  6561. control how `awk' does certain things. Those variables that are
  6562. specific to `gawk' are marked with an asterisk, `*'.
  6563.  
  6564. `CONVFMT'
  6565.      This string controls conversion of numbers to strings (*note
  6566.      Conversion of Strings and Numbers: Conversion.).  It works by
  6567.      being passed, in effect, as the first argument to the `sprintf'
  6568.      function (*note Built-in Functions for String Manipulation: String
  6569.      Functions.).  Its default value is `"%.6g"'.  `CONVFMT' was
  6570.      introduced by the POSIX standard.
  6571.  
  6572. `FIELDWIDTHS *'
  6573.      This is a space separated list of columns that tells `gawk' how to
  6574.      split input with fixed, columnar boundaries.  It is an
  6575.      experimental feature.  Assigning to `FIELDWIDTHS' overrides the
  6576.      use of `FS' for field splitting.  *Note Reading Fixed-width Data:
  6577.      Constant Size, for more information.
  6578.  
  6579.      If `gawk' is in compatibility mode (*note Command Line Options:
  6580.      Options.), then `FIELDWIDTHS' has no special meaning, and field
  6581.      splitting operations are done based exclusively on the value of
  6582.      `FS'.
  6583.  
  6584. `FS'
  6585.      `FS' is the input field separator (*note Specifying How Fields are
  6586.      Separated: Field Separators.).  The value is a single-character
  6587.      string or a multi-character regular expression that matches the
  6588.      separations between fields in an input record.  If the value is
  6589.      the null string (`""'), then each character in the record becomes
  6590.      a separate field.
  6591.  
  6592.      The default value is `" "', a string consisting of a single space.
  6593.      As a special exception, this value means that any sequence of
  6594.      spaces and tabs is a single separator.  It also causes spaces and
  6595.      tabs at the beginning and end of a record to be ignored.
  6596.  
  6597.      You can set the value of `FS' on the command line using the `-F'
  6598.      option:
  6599.  
  6600.           awk -F, 'PROGRAM' INPUT-FILES
  6601.  
  6602.      If `gawk' is using `FIELDWIDTHS' for field-splitting, assigning a
  6603.      value to `FS' will cause `gawk' to return to the normal,
  6604.      `FS'-based, field splitting. An easy way to do this is to simply
  6605.      say `FS = FS', perhaps with an explanatory comment.
  6606.  
  6607. `IGNORECASE *'
  6608.      If `IGNORECASE' is non-zero or non-null, then all string
  6609.      comparisons, and all regular expression matching are
  6610.      case-independent.  Thus, regexp matching with `~' and `!~', and
  6611.      the `gensub', `gsub', `index', `match', `split' and `sub'
  6612.      functions, record termination with `RS', and field splitting with
  6613.      `FS' all ignore case when doing their particular regexp operations.
  6614.      *Note Case-sensitivity in Matching: Case-sensitivity.
  6615.  
  6616.      If `gawk' is in compatibility mode (*note Command Line Options:
  6617.      Options.), then `IGNORECASE' has no special meaning, and string
  6618.      and regexp operations are always case-sensitive.
  6619.  
  6620. `OFMT'
  6621.      This string controls conversion of numbers to strings (*note
  6622.      Conversion of Strings and Numbers: Conversion.) for printing with
  6623.      the `print' statement.  It works by being passed, in effect, as
  6624.      the first argument to the `sprintf' function (*note Built-in
  6625.      Functions for String Manipulation: String Functions.).  Its
  6626.      default value is `"%.6g"'.  Earlier versions of `awk' also used
  6627.      `OFMT' to specify the format for converting numbers to strings in
  6628.      general expressions; this is now done by `CONVFMT'.
  6629.  
  6630. `OFS'
  6631.      This is the output field separator (*note Output Separators::.).
  6632.      It is output between the fields output by a `print' statement.  Its
  6633.      default value is `" "', a string consisting of a single space.
  6634.  
  6635. `ORS'
  6636.      This is the output record separator.  It is output at the end of
  6637.      every `print' statement.  Its default value is `"\n"'.  (*Note
  6638.      Output Separators::.)
  6639.  
  6640. `RS'
  6641.      This is `awk''s input record separator.  Its default value is a
  6642.      string containing a single newline character, which means that an
  6643.      input record consists of a single line of text.  It can also be
  6644.      the null string, in which case records are separated by runs of
  6645.      blank lines, or a regexp, in which case records are separated by
  6646.      matches of the regexp in the input text.  (*Note How Input is
  6647.      Split into Records: Records.)
  6648.  
  6649. `SUBSEP'
  6650.      `SUBSEP' is the subscript separator.  It has the default value of
  6651.      `"\034"', and is used to separate the parts of the indices of a
  6652.      multi-dimensional array.  Thus, the expression `foo["A", "B"]'
  6653.      really accesses `foo["A\034B"]' (*note Multi-dimensional Arrays:
  6654.      Multi-dimensional.).
  6655.  
  6656. 
  6657. File: gawk.info,  Node: Auto-set,  Next: ARGC and ARGV,  Prev: User-modified,  Up: Built-in Variables
  6658.  
  6659. Built-in Variables that Convey Information
  6660. ==========================================
  6661.  
  6662.    This is an alphabetical list of the variables that are set
  6663. automatically by `awk' on certain occasions in order to provide
  6664. information to your program.  Those variables that are specific to
  6665. `gawk' are marked with an asterisk, `*'.
  6666.  
  6667. `ARGC'
  6668. `ARGV'
  6669.      The command-line arguments available to `awk' programs are stored
  6670.      in an array called `ARGV'.  `ARGC' is the number of command-line
  6671.      arguments present.  *Note Other Command Line Arguments: Other
  6672.      Arguments.  Unlike most `awk' arrays, `ARGV' is indexed from zero
  6673.      to `ARGC' - 1.  For example:
  6674.  
  6675.           $ awk 'BEGIN {
  6676.           >        for (i = 0; i < ARGC; i++)
  6677.           >            print ARGV[i]
  6678.           >      }' inventory-shipped BBS-list
  6679.           -| awk
  6680.           -| inventory-shipped
  6681.           -| BBS-list
  6682.  
  6683.      In this example, `ARGV[0]' contains `"awk"', `ARGV[1]' contains
  6684.      `"inventory-shipped"', and `ARGV[2]' contains `"BBS-list"'.  The
  6685.      value of `ARGC' is three, one more than the index of the last
  6686.      element in `ARGV', since the elements are numbered from zero.
  6687.  
  6688.      The names `ARGC' and `ARGV', as well as the convention of indexing
  6689.      the array from zero to `ARGC' - 1, are derived from the C
  6690.      language's method of accessing command line arguments.  *Note
  6691.      Using `ARGC' and `ARGV': ARGC and ARGV, for information about how
  6692.      `awk' uses these variables.
  6693.  
  6694. `ARGIND *'
  6695.      The index in `ARGV' of the current file being processed.  Every
  6696.      time `gawk' opens a new data file for processing, it sets `ARGIND'
  6697.      to the index in `ARGV' of the file name.  When `gawk' is
  6698.      processing the input files, it is always true that `FILENAME ==
  6699.      ARGV[ARGIND]'.
  6700.  
  6701.      This variable is useful in file processing; it allows you to tell
  6702.      how far along you are in the list of data files, and to
  6703.      distinguish between successive instances of the same filename on
  6704.      the command line.
  6705.  
  6706.      While you can change the value of `ARGIND' within your `awk'
  6707.      program, `gawk' will automatically set it to a new value when the
  6708.      next file is opened.
  6709.  
  6710.      This variable is a `gawk' extension. In other `awk'
  6711.      implementations, or if `gawk' is in compatibility mode (*note
  6712.      Command Line Options: Options.), it is not special.
  6713.  
  6714. `ENVIRON'
  6715.      An associative array that contains the values of the environment.
  6716.      The array indices are the environment variable names; the values
  6717.      are the values of the particular environment variables.  For
  6718.      example, `ENVIRON["HOME"]' might be `/home/arnold'.  Changing this
  6719.      array does not affect the environment passed on to any programs
  6720.      that `awk' may spawn via redirection or the `system' function.
  6721.      (In a future version of `gawk', it may do so.)
  6722.  
  6723.      Some operating systems may not have environment variables.  On
  6724.      such systems, the `ENVIRON' array is empty (except for
  6725.      `ENVIRON["AWKPATH"]').
  6726.  
  6727. `ERRNO *'
  6728.      If a system error occurs either doing a redirection for `getline',
  6729.      during a read for `getline', or during a `close' operation, then
  6730.      `ERRNO' will contain a string describing the error.
  6731.  
  6732.      This variable is a `gawk' extension. In other `awk'
  6733.      implementations, or if `gawk' is in compatibility mode (*note
  6734.      Command Line Options: Options.), it is not special.
  6735.  
  6736. `FILENAME'
  6737.      This is the name of the file that `awk' is currently reading.
  6738.      When no data files are listed on the command line, `awk' reads
  6739.      from the standard input, and `FILENAME' is set to `"-"'.
  6740.      `FILENAME' is changed each time a new file is read (*note Reading
  6741.      Input Files: Reading Files.).  Inside a `BEGIN' rule, the value of
  6742.      `FILENAME' is `""', since there are no input files being processed
  6743.      yet.(1) (d.c.)
  6744.  
  6745. `FNR'
  6746.      `FNR' is the current record number in the current file.  `FNR' is
  6747.      incremented each time a new record is read (*note Explicit Input
  6748.      with `getline': Getline.).  It is reinitialized to zero each time
  6749.      a new input file is started.
  6750.  
  6751. `NF'
  6752.      `NF' is the number of fields in the current input record.  `NF' is
  6753.      set each time a new record is read, when a new field is created,
  6754.      or when `$0' changes (*note Examining Fields: Fields.).
  6755.  
  6756. `NR'
  6757.      This is the number of input records `awk' has processed since the
  6758.      beginning of the program's execution (*note How Input is Split
  6759.      into Records: Records.).  `NR' is set each time a new record is
  6760.      read.
  6761.  
  6762. `RLENGTH'
  6763.      `RLENGTH' is the length of the substring matched by the `match'
  6764.      function (*note Built-in Functions for String Manipulation: String
  6765.      Functions.).  `RLENGTH' is set by invoking the `match' function.
  6766.      Its value is the length of the matched string, or -1 if no match
  6767.      was found.
  6768.  
  6769. `RSTART'
  6770.      `RSTART' is the start-index in characters of the substring matched
  6771.      by the `match' function (*note Built-in Functions for String
  6772.      Manipulation: String Functions.).  `RSTART' is set by invoking the
  6773.      `match' function.  Its value is the position of the string where
  6774.      the matched substring starts, or zero if no match was found.
  6775.  
  6776. `RT *'
  6777.      `RT' is set each time a record is read. It contains the input text
  6778.      that matched the text denoted by `RS', the record separator.
  6779.  
  6780.      This variable is a `gawk' extension. In other `awk'
  6781.      implementations, or if `gawk' is in compatibility mode (*note
  6782.      Command Line Options: Options.), it is not special.
  6783.  
  6784.    A side note about `NR' and `FNR'.  `awk' simply increments both of
  6785. these variables each time it reads a record, instead of setting them to
  6786. the absolute value of the number of records read.  This means that your
  6787. program can change these variables, and their new values will be
  6788. incremented for each record (d.c.).  For example:
  6789.  
  6790.      $ echo '1
  6791.      > 2
  6792.      > 3
  6793.      > 4' | awk 'NR == 2 { NR = 17 }
  6794.      > { print NR }'
  6795.      -| 1
  6796.      -| 17
  6797.      -| 18
  6798.      -| 19
  6799.  
  6800. Before `FNR' was added to the `awk' language (*note Major Changes
  6801. between V7 and SVR3.1: V7/SVR3.1.), many `awk' programs used this
  6802. feature to track the number of records in a file by resetting `NR' to
  6803. zero when `FILENAME' changed.
  6804.  
  6805.    ---------- Footnotes ----------
  6806.  
  6807.    (1)  Some early implementations of Unix `awk' initialized `FILENAME'
  6808. to `"-"', even if there were data files to be processed. This behavior
  6809. was incorrect, and should not be relied upon in your programs.
  6810.  
  6811. 
  6812. File: gawk.info,  Node: ARGC and ARGV,  Prev: Auto-set,  Up: Built-in Variables
  6813.  
  6814. Using `ARGC' and `ARGV'
  6815. =======================
  6816.  
  6817.    In *Note Built-in Variables that Convey Information: Auto-set, you
  6818. saw this program describing the information contained in `ARGC' and
  6819. `ARGV':
  6820.  
  6821.      $ awk 'BEGIN {
  6822.      >        for (i = 0; i < ARGC; i++)
  6823.      >            print ARGV[i]
  6824.      >      }' inventory-shipped BBS-list
  6825.      -| awk
  6826.      -| inventory-shipped
  6827.      -| BBS-list
  6828.  
  6829. In this example, `ARGV[0]' contains `"awk"', `ARGV[1]' contains
  6830. `"inventory-shipped"', and `ARGV[2]' contains `"BBS-list"'.
  6831.  
  6832.    Notice that the `awk' program is not entered in `ARGV'.  The other
  6833. special command line options, with their arguments, are also not
  6834. entered.  But variable assignments on the command line *are* treated as
  6835. arguments, and do show up in the `ARGV' array.
  6836.  
  6837.    Your program can alter `ARGC' and the elements of `ARGV'.  Each time
  6838. `awk' reaches the end of an input file, it uses the next element of
  6839. `ARGV' as the name of the next input file.  By storing a different
  6840. string there, your program can change which files are read.  You can
  6841. use `"-"' to represent the standard input.  By storing additional
  6842. elements and incrementing `ARGC' you can cause additional files to be
  6843. read.
  6844.  
  6845.    If you decrease the value of `ARGC', that eliminates input files
  6846. from the end of the list.  By recording the old value of `ARGC'
  6847. elsewhere, your program can treat the eliminated arguments as something
  6848. other than file names.
  6849.  
  6850.    To eliminate a file from the middle of the list, store the null
  6851. string (`""') into `ARGV' in place of the file's name.  As a special
  6852. feature, `awk' ignores file names that have been replaced with the null
  6853. string.  You may also use the `delete' statement to remove elements from
  6854. `ARGV' (*note The `delete' Statement: Delete.).
  6855.  
  6856.    All of these actions are typically done from the `BEGIN' rule,
  6857. before actual processing of the input begins.  *Note Splitting a Large
  6858. File Into Pieces: Split Program, and see *Note Duplicating Output Into
  6859. Multiple Files: Tee Program, for an example of each way of removing
  6860. elements from `ARGV'.
  6861.  
  6862.    The following fragment processes `ARGV' in order to examine, and
  6863. then remove, command line options.
  6864.  
  6865.      BEGIN {
  6866.          for (i = 1; i < ARGC; i++) {
  6867.              if (ARGV[i] == "-v")
  6868.                  verbose = 1
  6869.              else if (ARGV[i] == "-d")
  6870.                  debug = 1
  6871.              else if (ARGV[i] ~ /^-?/) {
  6872.                  e = sprintf("%s: unrecognized option -- %c",
  6873.                          ARGV[0], substr(ARGV[i], 1, ,1))
  6874.                  print e > "/dev/stderr"
  6875.              } else
  6876.                  break
  6877.              delete ARGV[i]
  6878.          }
  6879.      }
  6880.  
  6881. 
  6882. File: gawk.info,  Node: Arrays,  Next: Built-in,  Prev: Built-in Variables,  Up: Top
  6883.  
  6884. Arrays in `awk'
  6885. ***************
  6886.  
  6887.    An "array" is a table of values, called "elements".  The elements of
  6888. an array are distinguished by their indices.  "Indices" may be either
  6889. numbers or strings.  `awk' maintains a single set of names that may be
  6890. used for naming variables, arrays and functions (*note User-defined
  6891. Functions: User-defined.).  Thus, you cannot have a variable and an
  6892. array with the same name in the same `awk' program.
  6893.  
  6894. * Menu:
  6895.  
  6896. * Array Intro::                 Introduction to Arrays
  6897. * Reference to Elements::       How to examine one element of an array.
  6898. * Assigning Elements::          How to change an element of an array.
  6899. * Array Example::               Basic Example of an Array
  6900. * Scanning an Array::           A variation of the `for' statement. It
  6901.                                 loops through the indices of an array's
  6902.                                 existing elements.
  6903. * Delete::                      The `delete' statement removes an element
  6904.                                 from an array.
  6905. * Numeric Array Subscripts::    How to use numbers as subscripts in
  6906.                                 `awk'.
  6907. * Uninitialized Subscripts::    Using Uninitialized variables as subscripts.
  6908. * Multi-dimensional::           Emulating multi-dimensional arrays in
  6909.                                 `awk'.
  6910. * Multi-scanning::              Scanning multi-dimensional arrays.
  6911.  
  6912. 
  6913. File: gawk.info,  Node: Array Intro,  Next: Reference to Elements,  Prev: Arrays,  Up: Arrays
  6914.  
  6915. Introduction to Arrays
  6916. ======================
  6917.  
  6918.    The `awk' language provides one-dimensional "arrays" for storing
  6919. groups of related strings or numbers.
  6920.  
  6921.    Every `awk' array must have a name.  Array names have the same
  6922. syntax as variable names; any valid variable name would also be a valid
  6923. array name.  But you cannot use one name in both ways (as an array and
  6924. as a variable) in one `awk' program.
  6925.  
  6926.    Arrays in `awk' superficially resemble arrays in other programming
  6927. languages; but there are fundamental differences.  In `awk', you don't
  6928. need to specify the size of an array before you start to use it.
  6929. Additionally, any number or string in `awk' may be used as an array
  6930. index, not just consecutive integers.
  6931.  
  6932.    In most other languages, you have to "declare" an array and specify
  6933. how many elements or components it contains.  In such languages, the
  6934. declaration causes a contiguous block of memory to be allocated for that
  6935. many elements.  An index in the array usually must be a positive
  6936. integer; for example, the index zero specifies the first element in the
  6937. array, which is actually stored at the beginning of the block of
  6938. memory.  Index one specifies the second element, which is stored in
  6939. memory right after the first element, and so on.  It is impossible to
  6940. add more elements to the array, because it has room for only as many
  6941. elements as you declared.  (Some languages allow arbitrary starting and
  6942. ending indices, e.g., `15 .. 27', but the size of the array is still
  6943. fixed when the array is declared.)
  6944.  
  6945.    A contiguous array of four elements might look like this,
  6946. conceptually, if the element values are eight, `"foo"', `""' and 30:
  6947.  
  6948.      +---------+---------+--------+---------+
  6949.      |    8    |  "foo"  |   ""   |    30   |    value
  6950.      +---------+---------+--------+---------+
  6951.           0         1         2         3        index
  6952.  
  6953. Only the values are stored; the indices are implicit from the order of
  6954. the values.  Eight is the value at index zero, because eight appears in
  6955. the position with zero elements before it.
  6956.  
  6957.    Arrays in `awk' are different: they are "associative".  This means
  6958. that each array is a collection of pairs: an index, and its
  6959. corresponding array element value:
  6960.  
  6961.      Element 4     Value 30
  6962.      Element 2     Value "foo"
  6963.      Element 1     Value 8
  6964.      Element 3     Value ""
  6965.  
  6966. We have shown the pairs in jumbled order because their order is
  6967. irrelevant.
  6968.  
  6969.    One advantage of associative arrays is that new pairs can be added
  6970. at any time.  For example, suppose we add to the above array a tenth
  6971. element whose value is `"number ten"'.  The result is this:
  6972.  
  6973.      Element 10    Value "number ten"
  6974.      Element 4     Value 30
  6975.      Element 2     Value "foo"
  6976.      Element 1     Value 8
  6977.      Element 3     Value ""
  6978.  
  6979. Now the array is "sparse", which just means some indices are missing:
  6980. it has elements 1-4 and 10, but doesn't have elements 5, 6, 7, 8, or 9.
  6981.  
  6982.    Another consequence of associative arrays is that the indices don't
  6983. have to be positive integers.  Any number, or even a string, can be an
  6984. index.  For example, here is an array which translates words from
  6985. English into French:
  6986.  
  6987.      Element "dog" Value "chien"
  6988.      Element "cat" Value "chat"
  6989.      Element "one" Value "un"
  6990.      Element 1     Value "un"
  6991.  
  6992. Here we decided to translate the number one in both spelled-out and
  6993. numeric form--thus illustrating that a single array can have both
  6994. numbers and strings as indices.  (In fact, array subscripts are always
  6995. strings; this is discussed in more detail in *Note Using Numbers to
  6996. Subscript Arrays: Numeric Array Subscripts.)
  6997.  
  6998.    When `awk' creates an array for you, e.g., with the `split' built-in
  6999. function, that array's indices are consecutive integers starting at one.
  7000. (*Note Built-in Functions for String Manipulation: String Functions.)
  7001.  
  7002. 
  7003. File: gawk.info,  Node: Reference to Elements,  Next: Assigning Elements,  Prev: Array Intro,  Up: Arrays
  7004.  
  7005. Referring to an Array Element
  7006. =============================
  7007.  
  7008.    The principal way of using an array is to refer to one of its
  7009. elements.  An array reference is an expression which looks like this:
  7010.  
  7011.      ARRAY[INDEX]
  7012.  
  7013. Here, ARRAY is the name of an array.  The expression INDEX is the index
  7014. of the element of the array that you want.
  7015.  
  7016.    The value of the array reference is the current value of that array
  7017. element.  For example, `foo[4.3]' is an expression for the element of
  7018. array `foo' at index `4.3'.
  7019.  
  7020.    If you refer to an array element that has no recorded value, the
  7021. value of the reference is `""', the null string.  This includes elements
  7022. to which you have not assigned any value, and elements that have been
  7023. deleted (*note The `delete' Statement: Delete.).  Such a reference
  7024. automatically creates that array element, with the null string as its
  7025. value.  (In some cases, this is unfortunate, because it might waste
  7026. memory inside `awk'.)
  7027.  
  7028.    You can find out if an element exists in an array at a certain index
  7029. with the expression:
  7030.  
  7031.      INDEX in ARRAY
  7032.  
  7033. This expression tests whether or not the particular index exists,
  7034. without the side effect of creating that element if it is not present.
  7035. The expression has the value one (true) if `ARRAY[INDEX]' exists, and
  7036. zero (false) if it does not exist.
  7037.  
  7038.    For example, to test whether the array `frequencies' contains the
  7039. index `2', you could write this statement:
  7040.  
  7041.      if (2 in frequencies)
  7042.          print "Subscript 2 is present."
  7043.  
  7044.    Note that this is *not* a test of whether or not the array
  7045. `frequencies' contains an element whose *value* is two.  (There is no
  7046. way to do that except to scan all the elements.)  Also, this *does not*
  7047. create `frequencies[2]', while the following (incorrect) alternative
  7048. would do so:
  7049.  
  7050.      if (frequencies[2] != "")
  7051.          print "Subscript 2 is present."
  7052.  
  7053. 
  7054. File: gawk.info,  Node: Assigning Elements,  Next: Array Example,  Prev: Reference to Elements,  Up: Arrays
  7055.  
  7056. Assigning Array Elements
  7057. ========================
  7058.  
  7059.    Array elements are lvalues: they can be assigned values just like
  7060. `awk' variables:
  7061.  
  7062.      ARRAY[SUBSCRIPT] = VALUE
  7063.  
  7064. Here ARRAY is the name of your array.  The expression SUBSCRIPT is the
  7065. index of the element of the array that you want to assign a value.  The
  7066. expression VALUE is the value you are assigning to that element of the
  7067. array.
  7068.  
  7069. 
  7070. File: gawk.info,  Node: Array Example,  Next: Scanning an Array,  Prev: Assigning Elements,  Up: Arrays
  7071.  
  7072. Basic Array Example
  7073. ===================
  7074.  
  7075.    The following program takes a list of lines, each beginning with a
  7076. line number, and prints them out in order of line number.  The line
  7077. numbers are not in order, however, when they are first read:  they are
  7078. scrambled.  This program sorts the lines by making an array using the
  7079. line numbers as subscripts.  It then prints out the lines in sorted
  7080. order of their numbers.  It is a very simple program, and gets confused
  7081. if it encounters repeated numbers, gaps, or lines that don't begin with
  7082. a number.
  7083.  
  7084.      {
  7085.        if ($1 > max)
  7086.          max = $1
  7087.        arr[$1] = $0
  7088.      }
  7089.      
  7090.      END {
  7091.        for (x = 1; x <= max; x++)
  7092.          print arr[x]
  7093.      }
  7094.  
  7095.    The first rule keeps track of the largest line number seen so far;
  7096. it also stores each line into the array `arr', at an index that is the
  7097. line's number.
  7098.  
  7099.    The second rule runs after all the input has been read, to print out
  7100. all the lines.
  7101.  
  7102.    When this program is run with the following input:
  7103.  
  7104.      5  I am the Five man
  7105.      2  Who are you?  The new number two!
  7106.      4  . . . And four on the floor
  7107.      1  Who is number one?
  7108.      3  I three you.
  7109.  
  7110. its output is this:
  7111.  
  7112.      1  Who is number one?
  7113.      2  Who are you?  The new number two!
  7114.      3  I three you.
  7115.      4  . . . And four on the floor
  7116.      5  I am the Five man
  7117.  
  7118.    If a line number is repeated, the last line with a given number
  7119. overrides the others.
  7120.  
  7121.    Gaps in the line numbers can be handled with an easy improvement to
  7122. the program's `END' rule:
  7123.  
  7124.      END {
  7125.        for (x = 1; x <= max; x++)
  7126.          if (x in arr)
  7127.            print arr[x]
  7128.      }
  7129.  
  7130. 
  7131. File: gawk.info,  Node: Scanning an Array,  Next: Delete,  Prev: Array Example,  Up: Arrays
  7132.  
  7133. Scanning All Elements of an Array
  7134. =================================
  7135.  
  7136.    In programs that use arrays, you often need a loop that executes
  7137. once for each element of an array.  In other languages, where arrays are
  7138. contiguous and indices are limited to positive integers, this is easy:
  7139. you can find all the valid indices by counting from the lowest index up
  7140. to the highest.  This technique won't do the job in `awk', since any
  7141. number or string can be an array index.  So `awk' has a special kind of
  7142. `for' statement for scanning an array:
  7143.  
  7144.      for (VAR in ARRAY)
  7145.        BODY
  7146.  
  7147. This loop executes BODY once for each index in ARRAY that your program
  7148. has previously used, with the variable VAR set to that index.
  7149.  
  7150.    Here is a program that uses this form of the `for' statement.  The
  7151. first rule scans the input records and notes which words appear (at
  7152. least once) in the input, by storing a one into the array `used' with
  7153. the word as index.  The second rule scans the elements of `used' to
  7154. find all the distinct words that appear in the input.  It prints each
  7155. word that is more than 10 characters long, and also prints the number of
  7156. such words.  *Note Built-in Functions for String Manipulation: String
  7157. Functions, for more information on the built-in function `length'.
  7158.  
  7159.      # Record a 1 for each word that is used at least once.
  7160.      {
  7161.          for (i = 1; i <= NF; i++)
  7162.              used[$i] = 1
  7163.      }
  7164.      
  7165.      # Find number of distinct words more than 10 characters long.
  7166.      END {
  7167.          for (x in used)
  7168.              if (length(x) > 10) {
  7169.                  ++num_long_words
  7170.                  print x
  7171.              }
  7172.          print num_long_words, "words longer than 10 characters"
  7173.      }
  7174.  
  7175. *Note Generating Word Usage Counts: Word Sorting, for a more detailed
  7176. example of this type.
  7177.  
  7178.    The order in which elements of the array are accessed by this
  7179. statement is determined by the internal arrangement of the array
  7180. elements within `awk' and cannot be controlled or changed.  This can
  7181. lead to problems if new elements are added to ARRAY by statements in
  7182. the loop body; you cannot predict whether or not the `for' loop will
  7183. reach them.  Similarly, changing VAR inside the loop may produce
  7184. strange results.  It is best to avoid such things.
  7185.  
  7186. 
  7187. File: gawk.info,  Node: Delete,  Next: Numeric Array Subscripts,  Prev: Scanning an Array,  Up: Arrays
  7188.  
  7189. The `delete' Statement
  7190. ======================
  7191.  
  7192.    You can remove an individual element of an array using the `delete'
  7193. statement:
  7194.  
  7195.      delete ARRAY[INDEX]
  7196.  
  7197.    Once you have deleted an array element, you can no longer obtain any
  7198. value the element once had.  It is as if you had never referred to it
  7199. and had never given it any value.
  7200.  
  7201.    Here is an example of deleting elements in an array:
  7202.  
  7203.      for (i in frequencies)
  7204.        delete frequencies[i]
  7205.  
  7206. This example removes all the elements from the array `frequencies'.
  7207.  
  7208.    If you delete an element, a subsequent `for' statement to scan the
  7209. array will not report that element, and the `in' operator to check for
  7210. the presence of that element will return zero (i.e. false):
  7211.  
  7212.      delete foo[4]
  7213.      if (4 in foo)
  7214.          print "This will never be printed"
  7215.  
  7216.    It is important to note that deleting an element is *not* the same
  7217. as assigning it a null value (the empty string, `""').
  7218.  
  7219.      foo[4] = ""
  7220.      if (4 in foo)
  7221.        print "This is printed, even though foo[4] is empty"
  7222.  
  7223.    It is not an error to delete an element that does not exist.
  7224.  
  7225.    You can delete all the elements of an array with a single statement,
  7226. by leaving off the subscript in the `delete' statement.
  7227.  
  7228.      delete ARRAY
  7229.  
  7230.    This ability is a `gawk' extension; it is not available in
  7231. compatibility mode (*note Command Line Options: Options.).
  7232.  
  7233.    Using this version of the `delete' statement is about three times
  7234. more efficient than the equivalent loop that deletes each element one
  7235. at a time.
  7236.  
  7237.    The following statement provides a portable, but non-obvious way to
  7238. clear out an array.
  7239.  
  7240.      # thanks to Michael Brennan for pointing this out
  7241.      split("", array)
  7242.  
  7243.    The `split' function (*note Built-in Functions for String
  7244. Manipulation: String Functions.) clears out the target array first.
  7245. This call asks it to split apart the null string. Since there is no
  7246. data to split out, the function simply clears the array and then
  7247. returns.
  7248.  
  7249. 
  7250. File: gawk.info,  Node: Numeric Array Subscripts,  Next: Uninitialized Subscripts,  Prev: Delete,  Up: Arrays
  7251.  
  7252. Using Numbers to Subscript Arrays
  7253. =================================
  7254.  
  7255.    An important aspect of arrays to remember is that *array subscripts
  7256. are always strings*.  If you use a numeric value as a subscript, it
  7257. will be converted to a string value before it is used for subscripting
  7258. (*note Conversion of Strings and Numbers: Conversion.).
  7259.  
  7260.    This means that the value of the built-in variable `CONVFMT' can
  7261. potentially affect how your program accesses elements of an array.  For
  7262. example:
  7263.  
  7264.      xyz = 12.153
  7265.      data[xyz] = 1
  7266.      CONVFMT = "%2.2f"
  7267.      if (xyz in data)
  7268.          printf "%s is in data\n", xyz
  7269.      else
  7270.          printf "%s is not in data\n", xyz
  7271.  
  7272. This prints `12.15 is not in data'.  The first statement gives `xyz' a
  7273. numeric value.  Assigning to `data[xyz]' subscripts `data' with the
  7274. string value `"12.153"' (using the default conversion value of
  7275. `CONVFMT', `"%.6g"'), and assigns one to `data["12.153"]'.  The program
  7276. then changes the value of `CONVFMT'.  The test `(xyz in data)'
  7277. generates a new string value from `xyz', this time `"12.15"', since the
  7278. value of `CONVFMT' only allows two significant digits.  This test fails,
  7279. since `"12.15"' is a different string from `"12.153"'.
  7280.  
  7281.    According to the rules for conversions (*note Conversion of Strings
  7282. and Numbers: Conversion.), integer values are always converted to
  7283. strings as integers, no matter what the value of `CONVFMT' may happen
  7284. to be.  So the usual case of:
  7285.  
  7286.      for (i = 1; i <= maxsub; i++)
  7287.          do something with array[i]
  7288.  
  7289. will work, no matter what the value of `CONVFMT'.
  7290.  
  7291.    Like many things in `awk', the majority of the time things work as
  7292. you would expect them to work.  But it is useful to have a precise
  7293. knowledge of the actual rules, since sometimes they can have a subtle
  7294. effect on your programs.
  7295.  
  7296. 
  7297. File: gawk.info,  Node: Uninitialized Subscripts,  Next: Multi-dimensional,  Prev: Numeric Array Subscripts,  Up: Arrays
  7298.  
  7299. Using Uninitialized Variables as Subscripts
  7300. ===========================================
  7301.  
  7302.    Suppose you want to print your input data in reverse order.  A
  7303. reasonable attempt at a program to do so (with some test data) might
  7304. look like this:
  7305.  
  7306.      $ echo 'line 1
  7307.      > line 2
  7308.      > line 3' | awk '{ l[lines] = $0; ++lines }
  7309.      > END {
  7310.      >     for (i = lines-1; i >= 0; --i)
  7311.      >        print l[i]
  7312.      > }'
  7313.      -| line 3
  7314.      -| line 2
  7315.  
  7316.    Unfortunately, the very first line of input data did not come out in
  7317. the output!
  7318.  
  7319.    At first glance, this program should have worked.  The variable
  7320. `lines' is uninitialized, and uninitialized variables have the numeric
  7321. value zero.  So, the value of `l[0]' should have been printed.
  7322.  
  7323.    The issue here is that subscripts for `awk' arrays are *always*
  7324. strings. And uninitialized variables, when used as strings, have the
  7325. value `""', not zero.  Thus, `line 1' ended up stored in `l[""]'.
  7326.  
  7327.    The following version of the program works correctly:
  7328.  
  7329.      { l[lines++] = $0 }
  7330.      END {
  7331.          for (i = lines - 1; i >= 0; --i)
  7332.             print l[i]
  7333.      }
  7334.  
  7335.    Here, the `++' forces `l' to be numeric, thus making the "old value"
  7336. numeric zero, which is then converted to `"0"' as the array subscript.
  7337.  
  7338.    As we have just seen, even though it is somewhat unusual, the null
  7339. string (`""') is a valid array subscript (d.c.). If `--lint' is provided
  7340. on the command line (*note Command Line Options: Options.), `gawk' will
  7341. warn about the use of the null string as a subscript.
  7342.  
  7343. 
  7344. File: gawk.info,  Node: Multi-dimensional,  Next: Multi-scanning,  Prev: Uninitialized Subscripts,  Up: Arrays
  7345.  
  7346. Multi-dimensional Arrays
  7347. ========================
  7348.  
  7349.    A multi-dimensional array is an array in which an element is
  7350. identified by a sequence of indices, instead of a single index.  For
  7351. example, a two-dimensional array requires two indices.  The usual way
  7352. (in most languages, including `awk') to refer to an element of a
  7353. two-dimensional array named `grid' is with `grid[X,Y]'.
  7354.  
  7355.    Multi-dimensional arrays are supported in `awk' through
  7356. concatenation of indices into one string.  What happens is that `awk'
  7357. converts the indices into strings (*note Conversion of Strings and
  7358. Numbers: Conversion.) and concatenates them together, with a separator
  7359. between them.  This creates a single string that describes the values
  7360. of the separate indices.  The combined string is used as a single index
  7361. into an ordinary, one-dimensional array.  The separator used is the
  7362. value of the built-in variable `SUBSEP'.
  7363.  
  7364.    For example, suppose we evaluate the expression `foo[5,12] = "value"'
  7365. when the value of `SUBSEP' is `"@"'.  The numbers five and 12 are
  7366. converted to strings and concatenated with an `@' between them,
  7367. yielding `"5@12"'; thus, the array element `foo["5@12"]' is set to
  7368. `"value"'.
  7369.  
  7370.    Once the element's value is stored, `awk' has no record of whether
  7371. it was stored with a single index or a sequence of indices.  The two
  7372. expressions `foo[5,12]' and `foo[5 SUBSEP 12]' are always equivalent.
  7373.  
  7374.    The default value of `SUBSEP' is the string `"\034"', which contains
  7375. a non-printing character that is unlikely to appear in an `awk' program
  7376. or in most input data.
  7377.  
  7378.    The usefulness of choosing an unlikely character comes from the fact
  7379. that index values that contain a string matching `SUBSEP' lead to
  7380. combined strings that are ambiguous.  Suppose that `SUBSEP' were `"@"';
  7381. then `foo["a@b", "c"]' and `foo["a", "b@c"]' would be indistinguishable
  7382. because both would actually be stored as `foo["a@b@c"]'.
  7383.  
  7384.    You can test whether a particular index-sequence exists in a
  7385. "multi-dimensional" array with the same operator `in' used for single
  7386. dimensional arrays.  Instead of a single index as the left-hand operand,
  7387. write the whole sequence of indices, separated by commas, in
  7388. parentheses:
  7389.  
  7390.      (SUBSCRIPT1, SUBSCRIPT2, ...) in ARRAY
  7391.  
  7392.    The following example treats its input as a two-dimensional array of
  7393. fields; it rotates this array 90 degrees clockwise and prints the
  7394. result.  It assumes that all lines have the same number of elements.
  7395.  
  7396.      awk '{
  7397.           if (max_nf < NF)
  7398.                max_nf = NF
  7399.           max_nr = NR
  7400.           for (x = 1; x <= NF; x++)
  7401.                vector[x, NR] = $x
  7402.      }
  7403.      
  7404.      END {
  7405.           for (x = 1; x <= max_nf; x++) {
  7406.                for (y = max_nr; y >= 1; --y)
  7407.                     printf("%s ", vector[x, y])
  7408.                printf("\n")
  7409.           }
  7410.      }'
  7411.  
  7412. When given the input:
  7413.  
  7414.      1 2 3 4 5 6
  7415.      2 3 4 5 6 1
  7416.      3 4 5 6 1 2
  7417.      4 5 6 1 2 3
  7418.  
  7419. it produces:
  7420.  
  7421.      4 3 2 1
  7422.      5 4 3 2
  7423.      6 5 4 3
  7424.      1 6 5 4
  7425.      2 1 6 5
  7426.      3 2 1 6
  7427.  
  7428. 
  7429. File: gawk.info,  Node: Multi-scanning,  Prev: Multi-dimensional,  Up: Arrays
  7430.  
  7431. Scanning Multi-dimensional Arrays
  7432. =================================
  7433.  
  7434.    There is no special `for' statement for scanning a
  7435. "multi-dimensional" array; there cannot be one, because in truth there
  7436. are no multi-dimensional arrays or elements; there is only a
  7437. multi-dimensional *way of accessing* an array.
  7438.  
  7439.    However, if your program has an array that is always accessed as
  7440. multi-dimensional, you can get the effect of scanning it by combining
  7441. the scanning `for' statement (*note Scanning All Elements of an Array:
  7442. Scanning an Array.) with the `split' built-in function (*note Built-in
  7443. Functions for String Manipulation: String Functions.).  It works like
  7444. this:
  7445.  
  7446.      for (combined in array) {
  7447.        split(combined, separate, SUBSEP)
  7448.        ...
  7449.      }
  7450.  
  7451. This sets `combined' to each concatenated, combined index in the array,
  7452. and splits it into the individual indices by breaking it apart where
  7453. the value of `SUBSEP' appears.  The split-out indices become the
  7454. elements of the array `separate'.
  7455.  
  7456.    Thus, suppose you have previously stored a value in `array[1,
  7457. "foo"]'; then an element with index `"1\034foo"' exists in `array'.
  7458. (Recall that the default value of `SUBSEP' is the character with code
  7459. 034.)  Sooner or later the `for' statement will find that index and do
  7460. an iteration with `combined' set to `"1\034foo"'.  Then the `split'
  7461. function is called as follows:
  7462.  
  7463.      split("1\034foo", separate, "\034")
  7464.  
  7465. The result of this is to set `separate[1]' to `"1"' and `separate[2]'
  7466. to `"foo"'.  Presto, the original sequence of separate indices has been
  7467. recovered.
  7468.  
  7469. 
  7470. File: gawk.info,  Node: Built-in,  Next: User-defined,  Prev: Arrays,  Up: Top
  7471.  
  7472. Built-in Functions
  7473. ******************
  7474.  
  7475.    "Built-in" functions are functions that are always available for
  7476. your `awk' program to call.  This chapter defines all the built-in
  7477. functions in `awk'; some of them are mentioned in other sections, but
  7478. they are summarized here for your convenience.  (You can also define
  7479. new functions yourself.  *Note User-defined Functions: User-defined.)
  7480.  
  7481. * Menu:
  7482.  
  7483. * Calling Built-in::            How to call built-in functions.
  7484. * Numeric Functions::           Functions that work with numbers, including
  7485.                                 `int', `sin' and `rand'.
  7486. * String Functions::            Functions for string manipulation, such as
  7487.                                 `split', `match', and
  7488.                                 `sprintf'.
  7489. * I/O Functions::               Functions for files and shell commands.
  7490. * Time Functions::              Functions for dealing with time stamps.
  7491.  
  7492. 
  7493. File: gawk.info,  Node: Calling Built-in,  Next: Numeric Functions,  Prev: Built-in,  Up: Built-in
  7494.  
  7495. Calling Built-in Functions
  7496. ==========================
  7497.  
  7498.    To call a built-in function, write the name of the function followed
  7499. by arguments in parentheses.  For example, `atan2(y + z, 1)' is a call
  7500. to the function `atan2', with two arguments.
  7501.  
  7502.    Whitespace is ignored between the built-in function name and the
  7503. open-parenthesis, but we recommend that you avoid using whitespace
  7504. there.  User-defined functions do not permit whitespace in this way, and
  7505. you will find it easier to avoid mistakes by following a simple
  7506. convention which always works: no whitespace after a function name.
  7507.  
  7508.    Each built-in function accepts a certain number of arguments.  In
  7509. some cases, arguments can be omitted. The defaults for omitted
  7510. arguments vary from function to function and are described under the
  7511. individual functions.  In some `awk' implementations, extra arguments
  7512. given to built-in functions are ignored.  However, in `gawk', it is a
  7513. fatal error to give extra arguments to a built-in function.
  7514.  
  7515.    When a function is called, expressions that create the function's
  7516. actual parameters are evaluated completely before the function call is
  7517. performed.  For example, in the code fragment:
  7518.  
  7519.      i = 4
  7520.      j = sqrt(i++)
  7521.  
  7522. the variable `i' is set to five before `sqrt' is called with a value of
  7523. four for its actual parameter.
  7524.  
  7525.    The order of evaluation of the expressions used for the function's
  7526. parameters is undefined.  Thus, you should not write programs that
  7527. assume that parameters are evaluated from left to right or from right
  7528. to left.  For example,
  7529.  
  7530.      i = 5
  7531.      j = atan2(i++, i *= 2)
  7532.  
  7533.    If the order of evaluation is left to right, then `i' first becomes
  7534. six, and then 12, and `atan2' is called with the two arguments six and
  7535. 12.  But if the order of evaluation is right to left, `i' first becomes
  7536. 10, and then 11, and `atan2' is called with the two arguments 11 and 10.
  7537.  
  7538. 
  7539. File: gawk.info,  Node: Numeric Functions,  Next: String Functions,  Prev: Calling Built-in,  Up: Built-in
  7540.  
  7541. Numeric Built-in Functions
  7542. ==========================
  7543.  
  7544.    Here is a full list of built-in functions that work with numbers.
  7545. Optional parameters are enclosed in square brackets ("[" and "]").
  7546.  
  7547. `int(X)'
  7548.      This produces the nearest integer to X, located between X and zero,
  7549.      truncated toward zero.
  7550.  
  7551.      For example, `int(3)' is three, `int(3.9)' is three, `int(-3.9)'
  7552.      is -3, and `int(-3)' is -3 as well.
  7553.  
  7554. `sqrt(X)'
  7555.      This gives you the positive square root of X.  It reports an error
  7556.      if X is negative.  Thus, `sqrt(4)' is two.
  7557.  
  7558. `exp(X)'
  7559.      This gives you the exponential of X (`e ^ X'), or reports an error
  7560.      if X is out of range.  The range of values X can have depends on
  7561.      your machine's floating point representation.
  7562.  
  7563. `log(X)'
  7564.      This gives you the natural logarithm of X, if X is positive;
  7565.      otherwise, it reports an error.
  7566.  
  7567. `sin(X)'
  7568.      This gives you the sine of X, with X in radians.
  7569.  
  7570. `cos(X)'
  7571.      This gives you the cosine of X, with X in radians.
  7572.  
  7573. `atan2(Y, X)'
  7574.      This gives you the arctangent of `Y / X' in radians.
  7575.  
  7576. `rand()'
  7577.      This gives you a random number.  The values of `rand' are
  7578.      uniformly-distributed between zero and one.  The value is never
  7579.      zero and never one.
  7580.  
  7581.      Often you want random integers instead.  Here is a user-defined
  7582.      function you can use to obtain a random non-negative integer less
  7583.      than N:
  7584.  
  7585.           function randint(n) {
  7586.                return int(n * rand())
  7587.           }
  7588.  
  7589.      The multiplication produces a random real number greater than zero
  7590.      and less than `n'.  We then make it an integer (using `int')
  7591.      between zero and `n' - 1, inclusive.
  7592.  
  7593.      Here is an example where a similar function is used to produce
  7594.      random integers between one and N.  This program prints a new
  7595.      random number for each input record.
  7596.  
  7597.           awk '
  7598.           # Function to roll a simulated die.
  7599.           function roll(n) { return 1 + int(rand() * n) }
  7600.           
  7601.           # Roll 3 six-sided dice and
  7602.           # print total number of points.
  7603.           {
  7604.                 printf("%d points\n",
  7605.                        roll(6)+roll(6)+roll(6))
  7606.           }'
  7607.  
  7608.      *Caution:* In most `awk' implementations, including `gawk', `rand'
  7609.      starts generating numbers from the same starting number, or
  7610.      "seed", each time you run `awk'.  Thus, a program will generate
  7611.      the same results each time you run it.  The numbers are random
  7612.      within one `awk' run, but predictable from run to run.  This is
  7613.      convenient for debugging, but if you want a program to do
  7614.      different things each time it is used, you must change the seed to
  7615.      a value that will be different in each run.  To do this, use
  7616.      `srand'.
  7617.  
  7618. `srand([X])'
  7619.      The function `srand' sets the starting point, or seed, for
  7620.      generating random numbers to the value X.
  7621.  
  7622.      Each seed value leads to a particular sequence of random
  7623.      numbers.(1) Thus, if you set the seed to the same value a second
  7624.      time, you will get the same sequence of random numbers again.
  7625.  
  7626.      If you omit the argument X, as in `srand()', then the current date
  7627.      and time of day are used for a seed.  This is the way to get random
  7628.      numbers that are truly unpredictable.
  7629.  
  7630.      The return value of `srand' is the previous seed.  This makes it
  7631.      easy to keep track of the seeds for use in consistently reproducing
  7632.      sequences of random numbers.
  7633.  
  7634.    ---------- Footnotes ----------
  7635.  
  7636.    (1)  Computer generated random numbers really are not truly random.
  7637. They are technically known as "pseudo-random."  This means that while
  7638. the numbers in a sequence appear to be random, you can in fact generate
  7639. the same sequence of random numbers over and over again.
  7640.  
  7641. 
  7642. File: gawk.info,  Node: String Functions,  Next: I/O Functions,  Prev: Numeric Functions,  Up: Built-in
  7643.  
  7644. Built-in Functions for String Manipulation
  7645. ==========================================
  7646.  
  7647.    The functions in this section look at or change the text of one or
  7648. more strings.  Optional parameters are enclosed in square brackets ("["
  7649. and "]").
  7650.  
  7651. `index(IN, FIND)'
  7652.      This searches the string IN for the first occurrence of the string
  7653.      FIND, and returns the position in characters where that occurrence
  7654.      begins in the string IN.  For example:
  7655.  
  7656.           $ awk 'BEGIN { print index("peanut", "an") }'
  7657.           -| 3
  7658.  
  7659.      If FIND is not found, `index' returns zero.  (Remember that string
  7660.      indices in `awk' start at one.)
  7661.  
  7662. `length([STRING])'
  7663.      This gives you the number of characters in STRING.  If STRING is a
  7664.      number, the length of the digit string representing that number is
  7665.      returned.  For example, `length("abcde")' is five.  By contrast,
  7666.      `length(15 * 35)' works out to three.  How?  Well, 15 * 35 = 525,
  7667.      and 525 is then converted to the string `"525"', which has three
  7668.      characters.
  7669.  
  7670.      If no argument is supplied, `length' returns the length of `$0'.
  7671.  
  7672.      In older versions of `awk', you could call the `length' function
  7673.      without any parentheses.  Doing so is marked as "deprecated" in the
  7674.      POSIX standard.  This means that while you can do this in your
  7675.      programs, it is a feature that can eventually be removed from a
  7676.      future version of the standard.  Therefore, for maximal
  7677.      portability of your `awk' programs, you should always supply the
  7678.      parentheses.
  7679.  
  7680. `match(STRING, REGEXP)'
  7681.      The `match' function searches the string, STRING, for the longest,
  7682.      leftmost substring matched by the regular expression, REGEXP.  It
  7683.      returns the character position, or "index", of where that
  7684.      substring begins (one, if it starts at the beginning of STRING).
  7685.      If no match is found, it returns zero.
  7686.  
  7687.      The `match' function sets the built-in variable `RSTART' to the
  7688.      index.  It also sets the built-in variable `RLENGTH' to the length
  7689.      in characters of the matched substring.  If no match is found,
  7690.      `RSTART' is set to zero, and `RLENGTH' to -1.
  7691.  
  7692.      For example:
  7693.  
  7694.           awk '{
  7695.                  if ($1 == "FIND")
  7696.                    regex = $2
  7697.                  else {
  7698.                    where = match($0, regex)
  7699.                    if (where != 0)
  7700.                      print "Match of", regex, "found at", \
  7701.                                where, "in", $0
  7702.                  }
  7703.           }'
  7704.  
  7705.      This program looks for lines that match the regular expression
  7706.      stored in the variable `regex'.  This regular expression can be
  7707.      changed.  If the first word on a line is `FIND', `regex' is
  7708.      changed to be the second word on that line.  Therefore, given:
  7709.  
  7710.           FIND ru+n
  7711.           My program runs
  7712.           but not very quickly
  7713.           FIND Melvin
  7714.           JF+KM
  7715.           This line is property of Reality Engineering Co.
  7716.           Melvin was here.
  7717.  
  7718.      `awk' prints:
  7719.  
  7720.           Match of ru+n found at 12 in My program runs
  7721.           Match of Melvin found at 1 in Melvin was here.
  7722.  
  7723. `split(STRING, ARRAY [, FIELDSEP])'
  7724.      This divides STRING into pieces separated by FIELDSEP, and stores
  7725.      the pieces in ARRAY.  The first piece is stored in `ARRAY[1]', the
  7726.      second piece in `ARRAY[2]', and so forth.  The string value of the
  7727.      third argument, FIELDSEP, is a regexp describing where to split
  7728.      STRING (much as `FS' can be a regexp describing where to split
  7729.      input records).  If the FIELDSEP is omitted, the value of `FS' is
  7730.      used.  `split' returns the number of elements created.
  7731.  
  7732.      The `split' function splits strings into pieces in a manner
  7733.      similar to the way input lines are split into fields.  For example:
  7734.  
  7735.           split("cul-de-sac", a, "-")
  7736.  
  7737.      splits the string `cul-de-sac' into three fields using `-' as the
  7738.      separator.  It sets the contents of the array `a' as follows:
  7739.  
  7740.           a[1] = "cul"
  7741.           a[2] = "de"
  7742.           a[3] = "sac"
  7743.  
  7744.      The value returned by this call to `split' is three.
  7745.  
  7746.      As with input field-splitting, when the value of FIELDSEP is
  7747.      `" "', leading and trailing whitespace is ignored, and the elements
  7748.      are separated by runs of whitespace.
  7749.  
  7750.      Also as with input field-splitting, if FIELDSEP is the null
  7751.      string, each individual character in the string is split into its
  7752.      own array element.  (This is a `gawk'-specific extension.)
  7753.  
  7754.      Recent implementations of `awk', including `gawk', allow the third
  7755.      argument to be a regexp constant (`/abc/'), as well as a string
  7756.      (d.c.).  The POSIX standard allows this as well.
  7757.  
  7758.      Before splitting the string, `split' deletes any previously
  7759.      existing elements in the array ARRAY (d.c.).
  7760.  
  7761. `sprintf(FORMAT, EXPRESSION1,...)'
  7762.      This returns (without printing) the string that `printf' would
  7763.      have printed out with the same arguments (*note Using `printf'
  7764.      Statements for Fancier Printing: Printf.).  For example:
  7765.  
  7766.           sprintf("pi = %.2f (approx.)", 22/7)
  7767.  
  7768.      returns the string `"pi = 3.14 (approx.)"'.
  7769.  
  7770. `sub(REGEXP, REPLACEMENT [, TARGET])'
  7771.      The `sub' function alters the value of TARGET.  It searches this
  7772.      value, which is treated as a string, for the leftmost longest
  7773.      substring matched by the regular expression, REGEXP, extending
  7774.      this match as far as possible.  Then the entire string is changed
  7775.      by replacing the matched text with REPLACEMENT.  The modified
  7776.      string becomes the new value of TARGET.
  7777.  
  7778.      This function is peculiar because TARGET is not simply used to
  7779.      compute a value, and not just any expression will do: it must be a
  7780.      variable, field or array element, so that `sub' can store a
  7781.      modified value there.  If this argument is omitted, then the
  7782.      default is to use and alter `$0'.
  7783.  
  7784.      For example:
  7785.  
  7786.           str = "water, water, everywhere"
  7787.           sub(/at/, "ith", str)
  7788.  
  7789.      sets `str' to `"wither, water, everywhere"', by replacing the
  7790.      leftmost, longest occurrence of `at' with `ith'.
  7791.  
  7792.      The `sub' function returns the number of substitutions made (either
  7793.      one or zero).
  7794.  
  7795.      If the special character `&' appears in REPLACEMENT, it stands for
  7796.      the precise substring that was matched by REGEXP.  (If the regexp
  7797.      can match more than one string, then this precise substring may
  7798.      vary.)  For example:
  7799.  
  7800.           awk '{ sub(/candidate/, "& and his wife"); print }'
  7801.  
  7802.      changes the first occurrence of `candidate' to `candidate and his
  7803.      wife' on each input line.
  7804.  
  7805.      Here is another example:
  7806.  
  7807.           awk 'BEGIN {
  7808.                   str = "daabaaa"
  7809.                   sub(/a*/, "c&c", str)
  7810.                   print str
  7811.           }'
  7812.           -| dcaacbaaa
  7813.  
  7814.      This shows how `&' can represent a non-constant string, and also
  7815.      illustrates the "leftmost, longest" rule in regexp matching (*note
  7816.      How Much Text Matches?: Leftmost Longest.).
  7817.  
  7818.      The effect of this special character (`&') can be turned off by
  7819.      putting a backslash before it in the string.  As usual, to insert
  7820.      one backslash in the string, you must write two backslashes.
  7821.      Therefore, write `\\&' in a string constant to include a literal
  7822.      `&' in the replacement.  For example, here is how to replace the
  7823.      first `|' on each line with an `&':
  7824.  
  7825.           awk '{ sub(/\|/, "\\&"); print }'
  7826.  
  7827.      *Note:* As mentioned above, the third argument to `sub' must be a
  7828.      variable, field or array reference.  Some versions of `awk' allow
  7829.      the third argument to be an expression which is not an lvalue.  In
  7830.      such a case, `sub' would still search for the pattern and return
  7831.      zero or one, but the result of the substitution (if any) would be
  7832.      thrown away because there is no place to put it.  Such versions of
  7833.      `awk' accept expressions like this:
  7834.  
  7835.           sub(/USA/, "United States", "the USA and Canada")
  7836.  
  7837.      This is considered erroneous in `gawk'.
  7838.  
  7839. `gsub(REGEXP, REPLACEMENT [, TARGET])'
  7840.      This is similar to the `sub' function, except `gsub' replaces
  7841.      *all* of the longest, leftmost, *non-overlapping* matching
  7842.      substrings it can find.  The `g' in `gsub' stands for "global,"
  7843.      which means replace everywhere.  For example:
  7844.  
  7845.           awk '{ gsub(/Britain/, "United Kingdom"); print }'
  7846.  
  7847.      replaces all occurrences of the string `Britain' with `United
  7848.      Kingdom' for all input records.
  7849.  
  7850.      The `gsub' function returns the number of substitutions made.  If
  7851.      the variable to be searched and altered, TARGET, is omitted, then
  7852.      the entire input record, `$0', is used.
  7853.  
  7854.      As in `sub', the characters `&' and `\' are special, and the third
  7855.      argument must be an lvalue.
  7856.  
  7857. `gensub(REGEXP, REPLACEMENT, HOW [, TARGET])'
  7858.      `gensub' is a general substitution function.  Like `sub' and
  7859.      `gsub', it searches the target string TARGET for matches of the
  7860.      regular expression REGEXP.  Unlike `sub' and `gsub', the modified
  7861.      string is returned as the result of the function, and the original
  7862.      target string is *not* changed.  If HOW is a string beginning with
  7863.      `g' or `G', then it replaces all matches of REGEXP with
  7864.      REPLACEMENT.  Otherwise, HOW is a number indicating which match of
  7865.      REGEXP to replace. If no TARGET is supplied, `$0' is used instead.
  7866.  
  7867.      `gensub' provides an additional feature that is not available in
  7868.      `sub' or `gsub': the ability to specify components of a regexp in
  7869.      the replacement text.  This is done by using parentheses in the
  7870.      regexp to mark the components, and then specifying `\N' in the
  7871.      replacement text, where N is a digit from one to nine.  For
  7872.      example:
  7873.  
  7874.           $ gawk '
  7875.           > BEGIN {
  7876.           >      a = "abc def"
  7877.           >      b = gensub(/(.+) (.+)/, "\\2 \\1", "g", a)
  7878.           >      print b
  7879.           > }'
  7880.           -| def abc
  7881.  
  7882.      As described above for `sub', you must type two backslashes in
  7883.      order to get one into the string.
  7884.  
  7885.      In the replacement text, the sequence `\0' represents the entire
  7886.      matched text, as does the character `&'.
  7887.  
  7888.      This example shows how you can use the third argument to control
  7889.      which match of the regexp should be changed.
  7890.  
  7891.           $ echo a b c a b c |
  7892.           > gawk '{ print gensub(/a/, "AA", 2) }'
  7893.           -| a b c AA b c
  7894.  
  7895.      In this case, `$0' is used as the default target string.  `gensub'
  7896.      returns the new string as its result, which is passed directly to
  7897.      `print' for printing.
  7898.  
  7899.      If the HOW argument is a string that does not begin with `g' or
  7900.      `G', or if it is a number that is less than zero, only one
  7901.      substitution is performed.
  7902.  
  7903.      `gensub' is a `gawk' extension; it is not available in
  7904.      compatibility mode (*note Command Line Options: Options.).
  7905.  
  7906. `substr(STRING, START [, LENGTH])'
  7907.      This returns a LENGTH-character-long substring of STRING, starting
  7908.      at character number START.  The first character of a string is
  7909.      character number one.  For example, `substr("washington", 5, 3)'
  7910.      returns `"ing"'.
  7911.  
  7912.      If LENGTH is not present, this function returns the whole suffix of
  7913.      STRING that begins at character number START.  For example,
  7914.      `substr("washington", 5)' returns `"ington"'.  The whole suffix is
  7915.      also returned if LENGTH is greater than the number of characters
  7916.      remaining in the string, counting from character number START.
  7917.  
  7918. `tolower(STRING)'
  7919.      This returns a copy of STRING, with each upper-case character in
  7920.      the string replaced with its corresponding lower-case character.
  7921.      Non-alphabetic characters are left unchanged.  For example,
  7922.      `tolower("MiXeD cAsE 123")' returns `"mixed case 123"'.
  7923.  
  7924. `toupper(STRING)'
  7925.      This returns a copy of STRING, with each lower-case character in
  7926.      the string replaced with its corresponding upper-case character.
  7927.      Non-alphabetic characters are left unchanged.  For example,
  7928.      `toupper("MiXeD cAsE 123")' returns `"MIXED CASE 123"'.
  7929.  
  7930. More About `\' and `&' with `sub', `gsub' and `gensub'
  7931. ------------------------------------------------------
  7932.  
  7933.    When using `sub', `gsub' or `gensub', and trying to get literal
  7934. backslashes and ampersands into the replacement text, you need to
  7935. remember that there are several levels of "escape processing" going on.
  7936.  
  7937.    First, there is the "lexical" level, which is when `awk' reads your
  7938. program, and builds an internal copy of your program that can be
  7939. executed.
  7940.  
  7941.    Then there is the run-time level, when `awk' actually scans the
  7942. replacement string to determine what to generate.
  7943.  
  7944.    At both levels, `awk' looks for a defined set of characters that can
  7945. come after a backslash.  At the lexical level, it looks for the escape
  7946. sequences listed in *Note Escape Sequences::.  Thus, for every `\' that
  7947. `awk' will process at the run-time level, you type two `\'s at the
  7948. lexical level.  When a character that is not valid for an escape
  7949. sequence follows the `\', Unix `awk' and `gawk' both simply remove the
  7950. initial `\', and put the following character into the string. Thus, for
  7951. example, `"a\qb"' is treated as `"aqb"'.
  7952.  
  7953.    At the run-time level, the various functions handle sequences of `\'
  7954. and `&' differently.  The situation is (sadly) somewhat complex.
  7955.  
  7956.    Historically, the `sub' and `gsub' functions treated the two
  7957. character sequence `\&' specially; this sequence was replaced in the
  7958. generated text with a single `&'.  Any other `\' within the REPLACEMENT
  7959. string that did not precede an `&' was passed through unchanged.  To
  7960. illustrate with a table:
  7961.  
  7962.       You type         `sub' sees          `sub' generates
  7963.       --------         ----------          ---------------
  7964.           `\&'              `&'            the matched text
  7965.          `\\&'             `\&'            a literal `&'
  7966.         `\\\&'             `\&'            a literal `&'
  7967.        `\\\\&'            `\\&'            a literal `\&'
  7968.       `\\\\\&'            `\\&'            a literal `\&'
  7969.      `\\\\\\&'           `\\\&'            a literal `\\&'
  7970.          `\\q'             `\q'            a literal `\q'
  7971.  
  7972. This table shows both the lexical level processing, where an odd number
  7973. of backslashes becomes an even number at the run time level, and the
  7974. run-time processing done by `sub'.  (For the sake of simplicity, the
  7975. rest of the tables below only show the case of even numbers of `\'s
  7976. entered at the lexical level.)
  7977.  
  7978.    The problem with the historical approach is that there is no way to
  7979. get a literal `\' followed by the matched text.
  7980.  
  7981.    The 1992 POSIX standard attempted to fix this problem. The standard
  7982. says that `sub' and `gsub' look for either a `\' or an `&' after the
  7983. `\'. If either one follows a `\', that character is output literally.
  7984. The interpretation of `\' and `&' then becomes like this:
  7985.  
  7986.       You type         `sub' sees          `sub' generates
  7987.       --------         ----------          ---------------
  7988.            `&'              `&'            the matched text
  7989.          `\\&'             `\&'            a literal `&'
  7990.        `\\\\&'            `\\&'            a literal `\', then the matched text
  7991.      `\\\\\\&'           `\\\&'            a literal `\&'
  7992.  
  7993. This would appear to solve the problem.  Unfortunately, the phrasing of
  7994. the standard is unusual. It says, in effect, that `\' turns off the
  7995. special meaning of any following character, but that for anything other
  7996. than `\' and `&', such special meaning is undefined.  This wording
  7997. leads to two problems.
  7998.  
  7999.   1. Backslashes must now be doubled in the REPLACEMENT string, breaking
  8000.      historical `awk' programs.
  8001.  
  8002.   2. To make sure that an `awk' program is portable, *every* character
  8003.      in the REPLACEMENT string must be preceded with a backslash.(1)
  8004.  
  8005.    The POSIX standard is under revision.(2) Because of the above
  8006. problems, proposed text for the revised standard reverts to rules that
  8007. correspond more closely to the original existing practice. The proposed
  8008. rules have special cases that make it possible to produce a `\'
  8009. preceding the matched text.
  8010.  
  8011.       You type         `sub' sees         `sub' generates
  8012.       --------         ----------         ---------------
  8013.      `\\\\\\&'           `\\\&'            a literal `\&'
  8014.        `\\\\&'            `\\&'            a literal `\', followed by the matched text
  8015.          `\\&'             `\&'            a literal `&'
  8016.          `\\q'             `\q'            a literal `\q'
  8017.  
  8018.    In a nutshell, at the run-time level, there are now three special
  8019. sequences of characters, `\\\&', `\\&' and `\&', whereas historically,
  8020. there was only one.  However, as in the historical case, any `\' that
  8021. is not part of one of these three sequences is not special, and appears
  8022. in the output literally.
  8023.  
  8024.    `gawk' 3.0 follows these proposed POSIX rules for `sub' and `gsub'.
  8025. Whether these proposed rules will actually become codified into the
  8026. standard is unknown at this point. Subsequent `gawk' releases will
  8027. track the standard and implement whatever the final version specifies;
  8028. this Info file will be updated as well.
  8029.  
  8030.    The rules for `gensub' are considerably simpler. At the run-time
  8031. level, whenever `gawk' sees a `\', if the following character is a
  8032. digit, then the text that matched the corresponding parenthesized
  8033. subexpression is placed in the generated output.  Otherwise, no matter
  8034. what the character after the `\' is, that character will appear in the
  8035. generated text, and the `\' will not.
  8036.  
  8037.        You type          `gensub' sees         `gensub' generates
  8038.        --------          -------------         ------------------
  8039.            `&'                    `&'            the matched text
  8040.          `\\&'                   `\&'            a literal `&'
  8041.         `\\\\'                   `\\'            a literal `\'
  8042.        `\\\\&'                  `\\&'            a literal `\', then the matched text
  8043.      `\\\\\\&'                 `\\\&'            a literal `\&'
  8044.          `\\q'                   `\q'            a literal `q'
  8045.  
  8046.    Because of the complexity of the lexical and run-time level
  8047. processing, and the special cases for `sub' and `gsub', we recommend
  8048. the use of `gawk' and `gensub' for when you have to do substitutions.
  8049.  
  8050.    ---------- Footnotes ----------
  8051.  
  8052.    (1)  This consequence was certainly unintended.
  8053.  
  8054.    (2)  As of December 1995, with final approval and publication
  8055. hopefully sometime in 1996.
  8056.  
  8057. 
  8058. File: gawk.info,  Node: I/O Functions,  Next: Time Functions,  Prev: String Functions,  Up: Built-in
  8059.  
  8060. Built-in Functions for Input/Output
  8061. ===================================
  8062.  
  8063.    The following functions are related to Input/Output (I/O).  Optional
  8064. parameters are enclosed in square brackets ("[" and "]").
  8065.  
  8066. `close(FILENAME)'
  8067.      Close the file FILENAME, for input or output.  The argument may
  8068.      alternatively be a shell command that was used for redirecting to
  8069.      or from a pipe; then the pipe is closed.  *Note Closing Input and
  8070.      Output Files and Pipes: Close Files And Pipes, for more
  8071.      information.
  8072.  
  8073. `fflush([FILENAME])'
  8074.      Flush any buffered output associated FILENAME, which is either a
  8075.      file opened for writing, or a shell command for redirecting output
  8076.      to a pipe.
  8077.  
  8078.      Many utility programs will "buffer" their output; they save
  8079.      information to be written to a disk file or terminal in memory,
  8080.      until there is enough for it to be worthwhile to send the data to
  8081.      the ouput device.  This is often more efficient than writing every
  8082.      little bit of information as soon as it is ready.  However,
  8083.      sometimes it is necessary to force a program to "flush" its
  8084.      buffers; that is, write the information to its destination, even
  8085.      if a buffer is not full.  This is the purpose of the `fflush'
  8086.      function; `gawk' too buffers its output, and the `fflush' function
  8087.      can be used to force `gawk' to flush its buffers.
  8088.  
  8089.      `fflush' is a recent (1994) addition to the Bell Labs research
  8090.      version of `awk'; it is not part of the POSIX standard, and will
  8091.      not be available if `--posix' has been specified on the command
  8092.      line (*note Command Line Options: Options.).
  8093.  
  8094.      `gawk' extends the `fflush' function in two ways.  This first is
  8095.      to allow no argument at all. In this case, the buffer for the
  8096.      standard output is flushed.  The second way is to allow the null
  8097.      string (`""') as the argument. In this case, the buffers for *all*
  8098.      open output files and pipes are flushed.
  8099.  
  8100.      `fflush' returns zero if the buffer was successfully flushed, and
  8101.      nonzero otherwise.
  8102.  
  8103. `system(COMMAND)'
  8104.      The system function allows the user to execute operating system
  8105.      commands and then return to the `awk' program.  The `system'
  8106.      function executes the command given by the string COMMAND.  It
  8107.      returns, as its value, the status returned by the command that was
  8108.      executed.
  8109.  
  8110.      For example, if the following fragment of code is put in your `awk'
  8111.      program:
  8112.  
  8113.           END {
  8114.                system("date | mail -s 'awk run done' root")
  8115.           }
  8116.  
  8117.      the system administrator will be sent mail when the `awk' program
  8118.      finishes processing input and begins its end-of-input processing.
  8119.  
  8120.      Note that redirecting `print' or `printf' into a pipe is often
  8121.      enough to accomplish your task.  However, if your `awk' program is
  8122.      interactive, `system' is useful for cranking up large
  8123.      self-contained programs, such as a shell or an editor.
  8124.  
  8125.      Some operating systems cannot implement the `system' function.
  8126.      `system' causes a fatal error if it is not supported.
  8127.  
  8128. Controlling Output Buffering with `system'
  8129. ------------------------------------------
  8130.  
  8131.    The `fflush' function provides explicit control over output
  8132. buffering for individual files and pipes.  However, its use is not
  8133. portable to many other `awk' implementations.  An alternative method to
  8134. flush output buffers is by calling `system' with a null string as its
  8135. argument:
  8136.  
  8137.      system("")   # flush output
  8138.  
  8139. `gawk' treats this use of the `system' function as a special case, and
  8140. is smart enough not to run a shell (or other command interpreter) with
  8141. the empty command.  Therefore, with `gawk', this idiom is not only
  8142. useful, it is efficient.  While this method should work with other
  8143. `awk' implementations, it will not necessarily avoid starting an
  8144. unnecessary shell.  (Other implementations may only flush the buffer
  8145. associated with the standard output, and not necessarily all buffered
  8146. output.)
  8147.  
  8148.    If you think about what a programmer expects, it makes sense that
  8149. `system' should flush any pending output.  The following program:
  8150.  
  8151.      BEGIN {
  8152.           print "first print"
  8153.           system("echo system echo")
  8154.           print "second print"
  8155.      }
  8156.  
  8157. must print
  8158.  
  8159.      first print
  8160.      system echo
  8161.      second print
  8162.  
  8163. and not
  8164.  
  8165.      system echo
  8166.      first print
  8167.      second print
  8168.  
  8169.    If `awk' did not flush its buffers before calling `system', the
  8170. latter (undesirable) output is what you would see.
  8171.  
  8172. 
  8173. File: gawk.info,  Node: Time Functions,  Prev: I/O Functions,  Up: Built-in
  8174.  
  8175. Functions for Dealing with Time Stamps
  8176. ======================================
  8177.  
  8178.    A common use for `awk' programs is the processing of log files
  8179. containing time stamp information, indicating when a particular log
  8180. record was written.  Many programs log their time stamp in the form
  8181. returned by the `time' system call, which is the number of seconds
  8182. since a particular epoch.  On POSIX systems, it is the number of
  8183. seconds since Midnight, January 1, 1970, UTC.
  8184.  
  8185.    In order to make it easier to process such log files, and to produce
  8186. useful reports, `gawk' provides two functions for working with time
  8187. stamps.  Both of these are `gawk' extensions; they are not specified in
  8188. the POSIX standard, nor are they in any other known version of `awk'.
  8189.  
  8190.    Optional parameters are enclosed in square brackets ("[" and "]").
  8191.  
  8192. `systime()'
  8193.      This function returns the current time as the number of seconds
  8194.      since the system epoch.  On POSIX systems, this is the number of
  8195.      seconds since Midnight, January 1, 1970, UTC.  It may be a
  8196.      different number on other systems.
  8197.  
  8198. `strftime([FORMAT [, TIMESTAMP]])'
  8199.      This function returns a string.  It is similar to the function of
  8200.      the same name in ANSI C.  The time specified by TIMESTAMP is used
  8201.      to produce a string, based on the contents of the FORMAT string.
  8202.      The TIMESTAMP is in the same format as the value returned by the
  8203.      `systime' function.  If no TIMESTAMP argument is supplied, `gawk'
  8204.      will use the current time of day as the time stamp.  If no FORMAT
  8205.      argument is supplied, `strftime' uses `"%a %b %d %H:%M:%S %Z %Y"'.
  8206.      This format string produces output (almost) equivalent to that of
  8207.      the `date' utility.  (Versions of `gawk' prior to 3.0 require the
  8208.      FORMAT argument.)
  8209.  
  8210.    The `systime' function allows you to compare a time stamp from a log
  8211. file with the current time of day.  In particular, it is easy to
  8212. determine how long ago a particular record was logged.  It also allows
  8213. you to produce log records using the "seconds since the epoch" format.
  8214.  
  8215.    The `strftime' function allows you to easily turn a time stamp into
  8216. human-readable information.  It is similar in nature to the `sprintf'
  8217. function (*note Built-in Functions for String Manipulation: String
  8218. Functions.), in that it copies non-format specification characters
  8219. verbatim to the returned string, while substituting date and time
  8220. values for format specifications in the FORMAT string.
  8221.  
  8222.    `strftime' is guaranteed by the ANSI C standard to support the
  8223. following date format specifications:
  8224.  
  8225. `%a'
  8226.      The locale's abbreviated weekday name.
  8227.  
  8228. `%A'
  8229.      The locale's full weekday name.
  8230.  
  8231. `%b'
  8232.      The locale's abbreviated month name.
  8233.  
  8234. `%B'
  8235.      The locale's full month name.
  8236.  
  8237. `%c'
  8238.      The locale's "appropriate" date and time representation.
  8239.  
  8240. `%d'
  8241.      The day of the month as a decimal number (01-31).
  8242.  
  8243. `%H'
  8244.      The hour (24-hour clock) as a decimal number (00-23).
  8245.  
  8246. `%I'
  8247.      The hour (12-hour clock) as a decimal number (01-12).
  8248.  
  8249. `%j'
  8250.      The day of the year as a decimal number (001-366).
  8251.  
  8252. `%m'
  8253.      The month as a decimal number (01-12).
  8254.  
  8255. `%M'
  8256.      The minute as a decimal number (00-59).
  8257.  
  8258. `%p'
  8259.      The locale's equivalent of the AM/PM designations associated with
  8260.      a 12-hour clock.
  8261.  
  8262. `%S'
  8263.      The second as a decimal number (00-61).(1)
  8264.  
  8265. `%U'
  8266.      The week number of the year (the first Sunday as the first day of
  8267.      week one) as a decimal number (00-53).
  8268.  
  8269. `%w'
  8270.      The weekday as a decimal number (0-6).  Sunday is day zero.
  8271.  
  8272. `%W'
  8273.      The week number of the year (the first Monday as the first day of
  8274.      week one) as a decimal number (00-53).
  8275.  
  8276. `%x'
  8277.      The locale's "appropriate" date representation.
  8278.  
  8279. `%X'
  8280.      The locale's "appropriate" time representation.
  8281.  
  8282. `%y'
  8283.      The year without century as a decimal number (00-99).
  8284.  
  8285. `%Y'
  8286.      The year with century as a decimal number (e.g., 1995).
  8287.  
  8288. `%Z'
  8289.      The time zone name or abbreviation, or no characters if no time
  8290.      zone is determinable.
  8291.  
  8292. `%%'
  8293.      A literal `%'.
  8294.  
  8295.    If a conversion specifier is not one of the above, the behavior is
  8296. undefined.(2)
  8297.  
  8298.    Informally, a "locale" is the geographic place in which a program is
  8299. meant to run.  For example, a common way to abbreviate the date
  8300. September 4, 1991 in the United States would be "9/4/91".  In many
  8301. countries in Europe, however, it would be abbreviated "4.9.91".  Thus,
  8302. the `%x' specification in a `"US"' locale might produce `9/4/91', while
  8303. in a `"EUROPE"' locale, it might produce `4.9.91'.  The ANSI C standard
  8304. defines a default `"C"' locale, which is an environment that is typical
  8305. of what most C programmers are used to.
  8306.  
  8307.    A public-domain C version of `strftime' is supplied with `gawk' for
  8308. systems that are not yet fully ANSI-compliant.  If that version is used
  8309. to compile `gawk' (*note Installing `gawk': Installation.), then the
  8310. following additional format specifications are available:
  8311.  
  8312. `%D'
  8313.      Equivalent to specifying `%m/%d/%y'.
  8314.  
  8315. `%e'
  8316.      The day of the month, padded with a space if it is only one digit.
  8317.  
  8318. `%h'
  8319.      Equivalent to `%b', above.
  8320.  
  8321. `%n'
  8322.      A newline character (ASCII LF).
  8323.  
  8324. `%r'
  8325.      Equivalent to specifying `%I:%M:%S %p'.
  8326.  
  8327. `%R'
  8328.      Equivalent to specifying `%H:%M'.
  8329.  
  8330. `%T'
  8331.      Equivalent to specifying `%H:%M:%S'.
  8332.  
  8333. `%t'
  8334.      A tab character.
  8335.  
  8336. `%k'
  8337.      The hour (24-hour clock) as a decimal number (0-23).  Single digit
  8338.      numbers are padded with a space.
  8339.  
  8340. `%l'
  8341.      The hour (12-hour clock) as a decimal number (1-12).  Single digit
  8342.      numbers are padded with a space.
  8343.  
  8344. `%C'
  8345.      The century, as a number between 00 and 99.
  8346.  
  8347. `%u'
  8348.      The weekday as a decimal number [1 (Monday)-7].
  8349.  
  8350. `%V'
  8351.      The week number of the year (the first Monday as the first day of
  8352.      week one) as a decimal number (01-53).  The method for determining
  8353.      the week number is as specified by ISO 8601 (to wit: if the week
  8354.      containing January 1 has four or more days in the new year, then
  8355.      it is week one, otherwise it is week 53 of the previous year and
  8356.      the next week is week one).
  8357.  
  8358. `%G'
  8359.      The year with century of the ISO week number, as a decimal number.
  8360.  
  8361.      For example, January 1, 1993, is in week 53 of 1992. Thus, the year
  8362.      of its ISO week number is 1992, even though its year is 1993.
  8363.      Similarly, December 31, 1973, is in week 1 of 1974. Thus, the year
  8364.      of its ISO week number is 1974, even though its year is 1973.
  8365.  
  8366. `%g'
  8367.      The year without century of the ISO week number, as a decimal
  8368.      number (00-99).
  8369.  
  8370. `%Ec %EC %Ex %Ey %EY %Od %Oe %OH %OI'
  8371. `%Om %OM %OS %Ou %OU %OV %Ow %OW %Oy'
  8372.      These are "alternate representations" for the specifications that
  8373.      use only the second letter (`%c', `%C', and so on).  They are
  8374.      recognized, but their normal representations are used.(3) (These
  8375.      facilitate compliance with the POSIX `date' utility.)
  8376.  
  8377. `%v'
  8378.      The date in VMS format (e.g., 20-JUN-1991).
  8379.  
  8380. `%z'
  8381.      The timezone offset in a +HHMM format (e.g., the format necessary
  8382.      to produce RFC-822/RFC-1036 date headers).
  8383.  
  8384.    This example is an `awk' implementation of the POSIX `date' utility.
  8385. Normally, the `date' utility prints the current date and time of day
  8386. in a well known format.  However, if you provide an argument to it that
  8387. begins with a `+', `date' will copy non-format specifier characters to
  8388. the standard output, and will interpret the current time according to
  8389. the format specifiers in the string.  For example:
  8390.  
  8391.      $ date '+Today is %A, %B %d, %Y.'
  8392.      -| Today is Thursday, July 11, 1991.
  8393.  
  8394.    Here is the `gawk' version of the `date' utility.  It has a shell
  8395. "wrapper", to handle the `-u' option, which requires that `date' run as
  8396. if the time zone was set to UTC.
  8397.  
  8398.      #! /bin/sh
  8399.      #
  8400.      # date --- approximate the P1003.2 'date' command
  8401.      
  8402.      case $1 in
  8403.      -u)  TZ=GMT0     # use UTC
  8404.           export TZ
  8405.           shift ;;
  8406.      esac
  8407.      
  8408.      gawk 'BEGIN  {
  8409.          format = "%a %b %d %H:%M:%S %Z %Y"
  8410.          exitval = 0
  8411.      
  8412.          if (ARGC > 2)
  8413.              exitval = 1
  8414.          else if (ARGC == 2) {
  8415.              format = ARGV[1]
  8416.              if (format ~ /^\+/)
  8417.                  format = substr(format, 2)   # remove leading +
  8418.          }
  8419.          print strftime(format)
  8420.          exit exitval
  8421.      }' "$@"
  8422.  
  8423.    ---------- Footnotes ----------
  8424.  
  8425.    (1)  Occasionally there are minutes in a year with one or two leap
  8426. seconds, which is why the seconds can go up to 61.
  8427.  
  8428.    (2)  This is because ANSI C leaves the behavior of the C version of
  8429. `strftime' undefined, and `gawk' will use the system's version of
  8430. `strftime' if it's there.  Typically, the conversion specifier will
  8431. either not appear in the returned string, or it will appear literally.
  8432.  
  8433.    (3)  If you don't understand any of this, don't worry about it;
  8434. these facilities are meant to make it easier to "internationalize"
  8435. programs.
  8436.  
  8437. 
  8438. File: gawk.info,  Node: User-defined,  Next: Invoking Gawk,  Prev: Built-in,  Up: Top
  8439.  
  8440. User-defined Functions
  8441. **********************
  8442.  
  8443.    Complicated `awk' programs can often be simplified by defining your
  8444. own functions.  User-defined functions can be called just like built-in
  8445. ones (*note Function Calls::.), but it is up to you to define them--to
  8446. tell `awk' what they should do.
  8447.  
  8448. * Menu:
  8449.  
  8450. * Definition Syntax::           How to write definitions and what they mean.
  8451. * Function Example::            An example function definition and what it
  8452.                                 does.
  8453. * Function Caveats::            Things to watch out for.
  8454. * Return Statement::            Specifying the value a function returns.
  8455.  
  8456. 
  8457. File: gawk.info,  Node: Definition Syntax,  Next: Function Example,  Prev: User-defined,  Up: User-defined
  8458.  
  8459. Function Definition Syntax
  8460. ==========================
  8461.  
  8462.    Definitions of functions can appear anywhere between the rules of an
  8463. `awk' program.  Thus, the general form of an `awk' program is extended
  8464. to include sequences of rules *and* user-defined function definitions.
  8465. There is no need in `awk' to put the definition of a function before
  8466. all uses of the function.  This is because `awk' reads the entire
  8467. program before starting to execute any of it.
  8468.  
  8469.    The definition of a function named NAME looks like this:
  8470.  
  8471.      function NAME(PARAMETER-LIST)
  8472.      {
  8473.           BODY-OF-FUNCTION
  8474.      }
  8475.  
  8476. NAME is the name of the function to be defined.  A valid function name
  8477. is like a valid variable name: a sequence of letters, digits and
  8478. underscores, not starting with a digit.  Within a single `awk' program,
  8479. any particular name can only be used as a variable, array or function.
  8480.  
  8481.    PARAMETER-LIST is a list of the function's arguments and local
  8482. variable names, separated by commas.  When the function is called, the
  8483. argument names are used to hold the argument values given in the call.
  8484. The local variables are initialized to the empty string.  A function
  8485. cannot have two parameters with the same name.
  8486.  
  8487.    The BODY-OF-FUNCTION consists of `awk' statements.  It is the most
  8488. important part of the definition, because it says what the function
  8489. should actually *do*.  The argument names exist to give the body a way
  8490. to talk about the arguments; local variables, to give the body places
  8491. to keep temporary values.
  8492.  
  8493.    Argument names are not distinguished syntactically from local
  8494. variable names; instead, the number of arguments supplied when the
  8495. function is called determines how many argument variables there are.
  8496. Thus, if three argument values are given, the first three names in
  8497. PARAMETER-LIST are arguments, and the rest are local variables.
  8498.  
  8499.    It follows that if the number of arguments is not the same in all
  8500. calls to the function, some of the names in PARAMETER-LIST may be
  8501. arguments on some occasions and local variables on others.  Another way
  8502. to think of this is that omitted arguments default to the null string.
  8503.  
  8504.    Usually when you write a function you know how many names you intend
  8505. to use for arguments and how many you intend to use as local variables.
  8506. It is conventional to place some extra space between the arguments and
  8507. the local variables, to document how your function is supposed to be
  8508. used.
  8509.  
  8510.    During execution of the function body, the arguments and local
  8511. variable values hide or "shadow" any variables of the same names used
  8512. in the rest of the program.  The shadowed variables are not accessible
  8513. in the function definition, because there is no way to name them while
  8514. their names have been taken away for the local variables.  All other
  8515. variables used in the `awk' program can be referenced or set normally
  8516. in the function's body.
  8517.  
  8518.    The arguments and local variables last only as long as the function
  8519. body is executing.  Once the body finishes, you can once again access
  8520. the variables that were shadowed while the function was running.
  8521.  
  8522.    The function body can contain expressions which call functions.  They
  8523. can even call this function, either directly or by way of another
  8524. function.  When this happens, we say the function is "recursive".
  8525.  
  8526.    In many `awk' implementations, including `gawk', the keyword
  8527. `function' may be abbreviated `func'.  However, POSIX only specifies
  8528. the use of the keyword `function'.  This actually has some practical
  8529. implications.  If `gawk' is in POSIX-compatibility mode (*note Command
  8530. Line Options: Options.), then the following statement will *not* define
  8531. a function:
  8532.  
  8533.      func foo() { a = sqrt($1) ; print a }
  8534.  
  8535. Instead it defines a rule that, for each record, concatenates the value
  8536. of the variable `func' with the return value of the function `foo'.  If
  8537. the resulting string is non-null, the action is executed.  This is
  8538. probably not what was desired.  (`awk' accepts this input as
  8539. syntactically valid, since functions may be used before they are defined
  8540. in `awk' programs.)
  8541.  
  8542.    To ensure that your `awk' programs are portable, always use the
  8543. keyword `function' when defining a function.
  8544.  
  8545. 
  8546. File: gawk.info,  Node: Function Example,  Next: Function Caveats,  Prev: Definition Syntax,  Up: User-defined
  8547.  
  8548. Function Definition Examples
  8549. ============================
  8550.  
  8551.    Here is an example of a user-defined function, called `myprint', that
  8552. takes a number and prints it in a specific format.
  8553.  
  8554.      function myprint(num)
  8555.      {
  8556.           printf "%6.3g\n", num
  8557.      }
  8558.  
  8559. To illustrate, here is an `awk' rule which uses our `myprint' function:
  8560.  
  8561.      $3 > 0     { myprint($3) }
  8562.  
  8563. This program prints, in our special format, all the third fields that
  8564. contain a positive number in our input.  Therefore, when given:
  8565.  
  8566.       1.2   3.4    5.6   7.8
  8567.       9.10 11.12 -13.14 15.16
  8568.      17.18 19.20  21.22 23.24
  8569.  
  8570. this program, using our function to format the results, prints:
  8571.  
  8572.         5.6
  8573.        21.2
  8574.  
  8575.    This function deletes all the elements in an array.
  8576.  
  8577.      function delarray(a,    i)
  8578.      {
  8579.          for (i in a)
  8580.             delete a[i]
  8581.      }
  8582.  
  8583.    When working with arrays, it is often necessary to delete all the
  8584. elements in an array and start over with a new list of elements (*note
  8585. The `delete' Statement: Delete.).  Instead of having to repeat this
  8586. loop everywhere in your program that you need to clear out an array,
  8587. your program can just call `delarray'.
  8588.  
  8589.    Here is an example of a recursive function.  It takes a string as an
  8590. input parameter, and returns the string in backwards order.
  8591.  
  8592.      function rev(str, start)
  8593.      {
  8594.          if (start == 0)
  8595.              return ""
  8596.      
  8597.          return (substr(str, start, 1) rev(str, start - 1))
  8598.      }
  8599.  
  8600.    If this function is in a file named `rev.awk', we can test it this
  8601. way:
  8602.  
  8603.      $ echo "Don't Panic!" |
  8604.      > gawk --source '{ print rev($0, length($0)) }' -f rev.awk
  8605.      -| !cinaP t'noD
  8606.  
  8607.    Here is an example that uses the built-in function `strftime'.
  8608. (*Note Functions for Dealing with Time Stamps: Time Functions, for more
  8609. information on `strftime'.) The C `ctime' function takes a timestamp
  8610. and returns it in a string, formatted in a well known fashion.  Here is
  8611. an `awk' version:
  8612.  
  8613.      # ctime.awk
  8614.      #
  8615.      # awk version of C ctime(3) function
  8616.      
  8617.      function ctime(ts,    format)
  8618.      {
  8619.          format = "%a %b %d %H:%M:%S %Z %Y"
  8620.          if (ts == 0)
  8621.              ts = systime()       # use current time as default
  8622.          return strftime(format, ts)
  8623.      }
  8624.  
  8625. 
  8626. File: gawk.info,  Node: Function Caveats,  Next: Return Statement,  Prev: Function Example,  Up: User-defined
  8627.  
  8628. Calling User-defined Functions
  8629. ==============================
  8630.  
  8631.    "Calling a function" means causing the function to run and do its
  8632. job.  A function call is an expression, and its value is the value
  8633. returned by the function.
  8634.  
  8635.    A function call consists of the function name followed by the
  8636. arguments in parentheses.  What you write in the call for the arguments
  8637. are `awk' expressions; each time the call is executed, these
  8638. expressions are evaluated, and the values are the actual arguments.  For
  8639. example, here is a call to `foo' with three arguments (the first being
  8640. a string concatenation):
  8641.  
  8642.      foo(x y, "lose", 4 * z)
  8643.  
  8644.    *Caution:* whitespace characters (spaces and tabs) are not allowed
  8645. between the function name and the open-parenthesis of the argument list.
  8646. If you write whitespace by mistake, `awk' might think that you mean to
  8647. concatenate a variable with an expression in parentheses.  However, it
  8648. notices that you used a function name and not a variable name, and
  8649. reports an error.
  8650.  
  8651.    When a function is called, it is given a *copy* of the values of its
  8652. arguments.  This is known as "call by value".  The caller may use a
  8653. variable as the expression for the argument, but the called function
  8654. does not know this: it only knows what value the argument had.  For
  8655. example, if you write this code:
  8656.  
  8657.      foo = "bar"
  8658.      z = myfunc(foo)
  8659.  
  8660. then you should not think of the argument to `myfunc' as being "the
  8661. variable `foo'."  Instead, think of the argument as the string value,
  8662. `"bar"'.
  8663.  
  8664.    If the function `myfunc' alters the values of its local variables,
  8665. this has no effect on any other variables.  Thus, if `myfunc' does this:
  8666.  
  8667.      function myfunc(str)
  8668.      {
  8669.        print str
  8670.        str = "zzz"
  8671.        print str
  8672.      }
  8673.  
  8674. to change its first argument variable `str', this *does not* change the
  8675. value of `foo' in the caller.  The role of `foo' in calling `myfunc'
  8676. ended when its value, `"bar"', was computed.  If `str' also exists
  8677. outside of `myfunc', the function body cannot alter this outer value,
  8678. because it is shadowed during the execution of `myfunc' and cannot be
  8679. seen or changed from there.
  8680.  
  8681.    However, when arrays are the parameters to functions, they are *not*
  8682. copied.  Instead, the array itself is made available for direct
  8683. manipulation by the function.  This is usually called "call by
  8684. reference".  Changes made to an array parameter inside the body of a
  8685. function *are* visible outside that function.  This can be *very*
  8686. dangerous if you do not watch what you are doing.  For example:
  8687.  
  8688.      function changeit(array, ind, nvalue)
  8689.      {
  8690.           array[ind] = nvalue
  8691.      }
  8692.      
  8693.      BEGIN {
  8694.          a[1] = 1; a[2] = 2; a[3] = 3
  8695.          changeit(a, 2, "two")
  8696.          printf "a[1] = %s, a[2] = %s, a[3] = %s\n",
  8697.                  a[1], a[2], a[3]
  8698.      }
  8699.  
  8700. This program prints `a[1] = 1, a[2] = two, a[3] = 3', because
  8701. `changeit' stores `"two"' in the second element of `a'.
  8702.  
  8703.    Some `awk' implementations allow you to call a function that has not
  8704. been defined, and only report a problem at run-time when the program
  8705. actually tries to call the function. For example:
  8706.  
  8707.      BEGIN {
  8708.          if (0)
  8709.              foo()
  8710.          else
  8711.              bar()
  8712.      }
  8713.      function bar() { ... }
  8714.      # note that `foo' is not defined
  8715.  
  8716. Since the `if' statement will never be true, it is not really a problem
  8717. that `foo' has not been defined.  Usually though, it is a problem if a
  8718. program calls an undefined function.
  8719.  
  8720.    If `--lint' has been specified (*note Command Line Options:
  8721. Options.), `gawk' will report about calls to undefined functions.
  8722.  
  8723. 
  8724. File: gawk.info,  Node: Return Statement,  Prev: Function Caveats,  Up: User-defined
  8725.  
  8726. The `return' Statement
  8727. ======================
  8728.  
  8729.    The body of a user-defined function can contain a `return' statement.
  8730. This statement returns control to the rest of the `awk' program.  It
  8731. can also be used to return a value for use in the rest of the `awk'
  8732. program.  It looks like this:
  8733.  
  8734.      return [EXPRESSION]
  8735.  
  8736.    The EXPRESSION part is optional.  If it is omitted, then the returned
  8737. value is undefined and, therefore, unpredictable.
  8738.  
  8739.    A `return' statement with no value expression is assumed at the end
  8740. of every function definition.  So if control reaches the end of the
  8741. function body, then the function returns an unpredictable value.  `awk'
  8742. will *not* warn you if you use the return value of such a function.
  8743.  
  8744.    Sometimes, you want to write a function for what it does, not for
  8745. what it returns.  Such a function corresponds to a `void' function in C
  8746. or to a `procedure' in Pascal.  Thus, it may be appropriate to not
  8747. return any value; you should simply bear in mind that if you use the
  8748. return value of such a function, you do so at your own risk.
  8749.  
  8750.    Here is an example of a user-defined function that returns a value
  8751. for the largest number among the elements of an array:
  8752.  
  8753.      function maxelt(vec,   i, ret)
  8754.      {
  8755.           for (i in vec) {
  8756.                if (ret == "" || vec[i] > ret)
  8757.                     ret = vec[i]
  8758.           }
  8759.           return ret
  8760.      }
  8761.  
  8762. You call `maxelt' with one argument, which is an array name.  The local
  8763. variables `i' and `ret' are not intended to be arguments; while there
  8764. is nothing to stop you from passing two or three arguments to `maxelt',
  8765. the results would be strange.  The extra space before `i' in the
  8766. function parameter list indicates that `i' and `ret' are not supposed
  8767. to be arguments.  This is a convention that you should follow when you
  8768. define functions.
  8769.  
  8770.    Here is a program that uses our `maxelt' function.  It loads an
  8771. array, calls `maxelt', and then reports the maximum number in that
  8772. array:
  8773.  
  8774.      awk '
  8775.      function maxelt(vec,   i, ret)
  8776.      {
  8777.           for (i in vec) {
  8778.                if (ret == "" || vec[i] > ret)
  8779.                     ret = vec[i]
  8780.           }
  8781.           return ret
  8782.      }
  8783.      
  8784.      # Load all fields of each record into nums.
  8785.      {
  8786.           for(i = 1; i <= NF; i++)
  8787.                nums[NR, i] = $i
  8788.      }
  8789.      
  8790.      END {
  8791.           print maxelt(nums)
  8792.      }'
  8793.  
  8794.    Given the following input:
  8795.  
  8796.       1 5 23 8 16
  8797.      44 3 5 2 8 26
  8798.      256 291 1396 2962 100
  8799.      -6 467 998 1101
  8800.      99385 11 0 225
  8801.  
  8802. our program tells us (predictably) that `99385' is the largest number
  8803. in our array.
  8804.  
  8805. 
  8806. File: gawk.info,  Node: Invoking Gawk,  Next: Library Functions,  Prev: User-defined,  Up: Top
  8807.  
  8808. Running `awk'
  8809. *************
  8810.  
  8811.    There are two ways to run `awk': with an explicit program, or with
  8812. one or more program files.  Here are templates for both of them; items
  8813. enclosed in `[...]' in these templates are optional.
  8814.  
  8815.    Besides traditional one-letter POSIX-style options, `gawk' also
  8816. supports GNU long options.
  8817.  
  8818.      awk [OPTIONS] -f progfile [`--'] FILE ...
  8819.      awk [OPTIONS] [`--'] 'PROGRAM' FILE ...
  8820.  
  8821.    It is possible to invoke `awk' with an empty program:
  8822.  
  8823.      $ awk '' datafile1 datafile2
  8824.  
  8825. Doing so makes little sense though; `awk' will simply exit silently
  8826. when given an empty program (d.c.).  If `--lint' has been specified on
  8827. the command line, `gawk' will issue a warning that the program is empty.
  8828.  
  8829. * Menu:
  8830.  
  8831. * Options::                     Command line options and their meanings.
  8832. * Other Arguments::             Input file names and variable assignments.
  8833. * AWKPATH Variable::            Searching directories for `awk' programs.
  8834. * Obsolete::                    Obsolete Options and/or features.
  8835. * Undocumented::                Undocumented Options and Features.
  8836. * Known Bugs::                  Known Bugs in `gawk'.
  8837.  
  8838. 
  8839. File: gawk.info,  Node: Options,  Next: Other Arguments,  Prev: Invoking Gawk,  Up: Invoking Gawk
  8840.  
  8841. Command Line Options
  8842. ====================
  8843.  
  8844.    Options begin with a dash, and consist of a single character.  GNU
  8845. style long options consist of two dashes and a keyword.  The keyword
  8846. can be abbreviated, as long the abbreviation allows the option to be
  8847. uniquely identified.  If the option takes an argument, then the keyword
  8848. is either immediately followed by an equals sign (`=') and the
  8849. argument's value, or the keyword and the argument's value are separated
  8850. by whitespace.  For brevity, the discussion below only refers to the
  8851. traditional short options; however the long and short options are
  8852. interchangeable in all contexts.
  8853.  
  8854.    Each long option for `gawk' has a corresponding POSIX-style option.
  8855. The options and their meanings are as follows:
  8856.  
  8857. `-F FS'
  8858. `--field-separator FS'
  8859.      Sets the `FS' variable to FS (*note Specifying How Fields are
  8860.      Separated: Field Separators.).
  8861.  
  8862. `-f SOURCE-FILE'
  8863. `--file SOURCE-FILE'
  8864.      Indicates that the `awk' program is to be found in SOURCE-FILE
  8865.      instead of in the first non-option argument.
  8866.  
  8867. `-v VAR=VAL'
  8868. `--assign VAR=VAL'
  8869.      Sets the variable VAR to the value VAL *before* execution of the
  8870.      program begins.  Such variable values are available inside the
  8871.      `BEGIN' rule (*note Other Command Line Arguments: Other
  8872.      Arguments.).
  8873.  
  8874.      The `-v' option can only set one variable, but you can use it more
  8875.      than once, setting another variable each time, like this: `awk
  8876.      -v foo=1 -v bar=2 ...'.
  8877.  
  8878. `-mf=NNN'
  8879. `-mr=NNN'
  8880.      Set various memory limits to the value NNN.  The `f' flag sets the
  8881.      maximum number of fields, and the `r' flag sets the maximum record
  8882.      size.  These two flags and the `-m' option are from the Bell Labs
  8883.      research version of Unix `awk'.  They are provided for
  8884.      compatibility, but otherwise ignored by `gawk', since `gawk' has
  8885.      no predefined limits.
  8886.  
  8887. `-W GAWK-OPT'
  8888.      Following the POSIX standard, options that are implementation
  8889.      specific are supplied as arguments to the `-W' option.  With
  8890.      `gawk', these arguments may be separated by commas, or quoted and
  8891.      separated by whitespace.  Case is ignored when processing these
  8892.      options.  These options also have corresponding GNU style long
  8893.      options.  See below.
  8894.  
  8895. `--'
  8896.      Signals the end of the command line options.  The following
  8897.      arguments are not treated as options even if they begin with `-'.
  8898.      This interpretation of `--' follows the POSIX argument parsing
  8899.      conventions.
  8900.  
  8901.      This is useful if you have file names that start with `-', or in
  8902.      shell scripts, if you have file names that will be specified by
  8903.      the user which could start with `-'.
  8904.  
  8905.    The following `gawk'-specific options are available:
  8906.  
  8907. `-W traditional'
  8908. `-W compat'
  8909. `--traditional'
  8910. `--compat'
  8911.      Specifies "compatibility mode", in which the GNU extensions to the
  8912.      `awk' language are disabled, so that `gawk' behaves just like the
  8913.      Bell Labs research version of Unix `awk'.  `--traditional' is the
  8914.      preferred form of this option.  *Note Extensions in `gawk' Not in
  8915.      POSIX `awk': POSIX/GNU, which summarizes the extensions.  Also see
  8916.      *Note Downward Compatibility and Debugging: Compatibility Mode.
  8917.  
  8918. `-W copyleft'
  8919. `-W copyright'
  8920. `--copyleft'
  8921. `--copyright'
  8922.      Print the short version of the General Public License.  This
  8923.      option may disappear in a future version of `gawk'.
  8924.  
  8925. `-W help'
  8926. `-W usage'
  8927. `--help'
  8928. `--usage'
  8929.      Print a "usage" message summarizing the short and long style
  8930.      options that `gawk' accepts, and then exit.
  8931.  
  8932. `-W lint'
  8933. `--lint'
  8934.      Warn about constructs that are dubious or non-portable to other
  8935.      `awk' implementations.  Some warnings are issued when `gawk' first
  8936.      reads your program.  Others are issued at run-time, as your
  8937.      program executes.
  8938.  
  8939. `-W lint-old'
  8940. `--lint-old'
  8941.      Warn about constructs that are not available in the original
  8942.      Version 7 Unix version of `awk' (*note Major Changes between V7
  8943.      and SVR3.1: V7/SVR3.1.).
  8944.  
  8945. `-W posix'
  8946. `--posix'
  8947.      Operate in strict POSIX mode.  This disables all `gawk' extensions
  8948.      (just like `--traditional'), and adds the following additional
  8949.      restrictions:
  8950.  
  8951.         * `\x' escape sequences are not recognized (*note Escape
  8952.           Sequences::.).
  8953.  
  8954.         * The synonym `func' for the keyword `function' is not
  8955.           recognized (*note Function Definition Syntax: Definition
  8956.           Syntax.).
  8957.  
  8958.         * The operators `**' and `**=' cannot be used in place of `^'
  8959.           and `^=' (*note Arithmetic Operators: Arithmetic Ops., and
  8960.           also *note Assignment Expressions: Assignment Ops.).
  8961.  
  8962.         * Specifying `-Ft' on the command line does not set the value
  8963.           of `FS' to be a single tab character (*note Specifying How
  8964.           Fields are Separated: Field Separators.).
  8965.  
  8966.         * The `fflush' built-in function is not supported (*note
  8967.           Built-in Functions for Input/Output: I/O Functions.).
  8968.  
  8969.      If you supply both `--traditional' and `--posix' on the command
  8970.      line, `--posix' will take precedence. `gawk' will also issue a
  8971.      warning if both options are supplied.
  8972.  
  8973. `-W re-interval'
  8974. `--re-interval'
  8975.      Allow interval expressions (*note Regular Expression Operators:
  8976.      Regexp Operators.), in regexps.  Because interval expressions were
  8977.      traditionally not available in `awk', `gawk' does not provide them
  8978.      by default. This prevents old `awk' programs from breaking.
  8979.  
  8980. `-W source PROGRAM-TEXT'
  8981. `--source PROGRAM-TEXT'
  8982.      Program source code is taken from the PROGRAM-TEXT.  This option
  8983.      allows you to mix source code in files with source code that you
  8984.      enter on the command line. This is particularly useful when you
  8985.      have library functions that you wish to use from your command line
  8986.      programs (*note The `AWKPATH' Environment Variable: AWKPATH
  8987.      Variable.).
  8988.  
  8989. `-W version'
  8990. `--version'
  8991.      Prints version information for this particular copy of `gawk'.
  8992.      This allows you to determine if your copy of `gawk' is up to date
  8993.      with respect to whatever the Free Software Foundation is currently
  8994.      distributing.  It is also useful for bug reports (*note Reporting
  8995.      Problems and Bugs: Bugs.).
  8996.  
  8997.    Any other options are flagged as invalid with a warning message, but
  8998. are otherwise ignored.
  8999.  
  9000.    In compatibility mode, as a special case, if the value of FS supplied
  9001. to the `-F' option is `t', then `FS' is set to the tab character
  9002. (`"\t"').  This is only true for `--traditional', and not for `--posix'
  9003. (*note Specifying How Fields are Separated: Field Separators.).
  9004.  
  9005.    The `-f' option may be used more than once on the command line.  If
  9006. it is, `awk' reads its program source from all of the named files, as
  9007. if they had been concatenated together into one big file.  This is
  9008. useful for creating libraries of `awk' functions.  Useful functions can
  9009. be written once, and then retrieved from a standard place, instead of
  9010. having to be included into each individual program.
  9011.  
  9012.    You can type in a program at the terminal and still use library
  9013. functions, by specifying `-f /dev/tty'.  `awk' will read a file from
  9014. the terminal to use as part of the `awk' program.  After typing your
  9015. program, type `Control-d' (the end-of-file character) to terminate it.
  9016. (You may also use `-f -' to read program source from the standard
  9017. input, but then you will not be able to also use the standard input as a
  9018. source of data.)
  9019.  
  9020.    Because it is clumsy using the standard `awk' mechanisms to mix
  9021. source file and command line `awk' programs, `gawk' provides the
  9022. `--source' option.  This does not require you to pre-empt the standard
  9023. input for your source code, and allows you to easily mix command line
  9024. and library source code (*note The `AWKPATH' Environment Variable:
  9025. AWKPATH Variable.).
  9026.  
  9027.    If no `-f' or `--source' option is specified, then `gawk' will use
  9028. the first non-option command line argument as the text of the program
  9029. source code.
  9030.  
  9031.    If the environment variable `POSIXLY_CORRECT' exists, then `gawk'
  9032. will behave in strict POSIX mode, exactly as if you had supplied the
  9033. `--posix' command line option.  Many GNU programs look for this
  9034. environment variable to turn on strict POSIX mode. If you supply
  9035. `--lint' on the command line, and `gawk' turns on POSIX mode because of
  9036. `POSIXLY_CORRECT', then it will print a warning message indicating that
  9037. POSIX mode is in effect.
  9038.  
  9039.    You would typically set this variable in your shell's startup file.
  9040. For a Bourne compatible shell (such as Bash), you would add these lines
  9041. to the `.profile' file in your home directory.
  9042.  
  9043.      POSIXLY_CORRECT=true
  9044.      export POSIXLY_CORRECT
  9045.  
  9046.    For a `csh' compatible shell,(1) you would add this line to the
  9047. `.login' file in your home directory.
  9048.  
  9049.      setenv POSIXLY_CORRECT true
  9050.  
  9051.    ---------- Footnotes ----------
  9052.  
  9053.    (1)  Not recommended.
  9054.  
  9055. 
  9056. File: gawk.info,  Node: Other Arguments,  Next: AWKPATH Variable,  Prev: Options,  Up: Invoking Gawk
  9057.  
  9058. Other Command Line Arguments
  9059. ============================
  9060.  
  9061.    Any additional arguments on the command line are normally treated as
  9062. input files to be processed in the order specified.   However, an
  9063. argument that has the form `VAR=VALUE', assigns the value VALUE to the
  9064. variable VAR--it does not specify a file at all.
  9065.  
  9066.    All these arguments are made available to your `awk' program in the
  9067. `ARGV' array (*note Built-in Variables::.).  Command line options and
  9068. the program text (if present) are omitted from `ARGV'.  All other
  9069. arguments, including variable assignments, are included.   As each
  9070. element of `ARGV' is processed, `gawk' sets the variable `ARGIND' to
  9071. the index in `ARGV' of the current element.
  9072.  
  9073.    The distinction between file name arguments and variable-assignment
  9074. arguments is made when `awk' is about to open the next input file.  At
  9075. that point in execution, it checks the "file name" to see whether it is
  9076. really a variable assignment; if so, `awk' sets the variable instead of
  9077. reading a file.
  9078.  
  9079.    Therefore, the variables actually receive the given values after all
  9080. previously specified files have been read.  In particular, the values of
  9081. variables assigned in this fashion are *not* available inside a `BEGIN'
  9082. rule (*note The `BEGIN' and `END' Special Patterns: BEGIN/END.), since
  9083. such rules are run before `awk' begins scanning the argument list.
  9084.  
  9085.    The variable values given on the command line are processed for
  9086. escape sequences (d.c.) (*note Escape Sequences::.).
  9087.  
  9088.    In some earlier implementations of `awk', when a variable assignment
  9089. occurred before any file names, the assignment would happen *before*
  9090. the `BEGIN' rule was executed.  `awk''s behavior was thus inconsistent;
  9091. some command line assignments were available inside the `BEGIN' rule,
  9092. while others were not.  However, some applications came to depend upon
  9093. this "feature."  When `awk' was changed to be more consistent, the `-v'
  9094. option was added to accommodate applications that depended upon the old
  9095. behavior.
  9096.  
  9097.    The variable assignment feature is most useful for assigning to
  9098. variables such as `RS', `OFS', and `ORS', which control input and
  9099. output formats, before scanning the data files.  It is also useful for
  9100. controlling state if multiple passes are needed over a data file.  For
  9101. example:
  9102.  
  9103.      awk 'pass == 1  { PASS 1 STUFF }
  9104.           pass == 2  { PASS 2 STUFF }' pass=1 mydata pass=2 mydata
  9105.  
  9106.    Given the variable assignment feature, the `-F' option for setting
  9107. the value of `FS' is not strictly necessary.  It remains for historical
  9108. compatibility.
  9109.  
  9110. 
  9111. File: gawk.info,  Node: AWKPATH Variable,  Next: Obsolete,  Prev: Other Arguments,  Up: Invoking Gawk
  9112.  
  9113. The `AWKPATH' Environment Variable
  9114. ==================================
  9115.  
  9116.    The previous section described how `awk' program files can be named
  9117. on the command line with the `-f' option.  In most `awk'
  9118. implementations, you must supply a precise path name for each program
  9119. file, unless the file is in the current directory.
  9120.  
  9121.    But in `gawk', if the file name supplied to the `-f' option does not
  9122. contain a `/', then `gawk' searches a list of directories (called the
  9123. "search path"), one by one, looking for a file with the specified name.
  9124.  
  9125.    The search path is a string consisting of directory names separated
  9126. by colons.  `gawk' gets its search path from the `AWKPATH' environment
  9127. variable.  If that variable does not exist, `gawk' uses a default path,
  9128. which is `.:/usr/local/share/awk'.(1) (Programs written for use by
  9129. system administrators should use an `AWKPATH' variable that does not
  9130. include the current directory, `.'.)
  9131.  
  9132.    The search path feature is particularly useful for building up
  9133. libraries of useful `awk' functions.  The library files can be placed
  9134. in a standard directory that is in the default path, and then specified
  9135. on the command line with a short file name.  Otherwise, the full file
  9136. name would have to be typed for each file.
  9137.  
  9138.    By using both the `--source' and `-f' options, your command line
  9139. `awk' programs can use facilities in `awk' library files.  *Note A
  9140. Library of `awk' Functions: Library Functions.
  9141.  
  9142.    Path searching is not done if `gawk' is in compatibility mode.  This
  9143. is true for both `--traditional' and `--posix'.  *Note Command Line
  9144. Options: Options.
  9145.  
  9146.    *Note:* if you want files in the current directory to be found, you
  9147. must include the current directory in the path, either by including `.'
  9148. explicitly in the path, or by writing a null entry in the path.  (A
  9149. null entry is indicated by starting or ending the path with a colon, or
  9150. by placing two colons next to each other (`::').)  If the current
  9151. directory is not included in the path, then files cannot be found in
  9152. the current directory.  This path search mechanism is identical to the
  9153. shell's.
  9154.  
  9155.    Starting with version 3.0, if `AWKPATH' is not defined in the
  9156. environment, `gawk' will place its default search path into
  9157. `ENVIRON["AWKPATH"]'. This makes it easy to determine the actual search
  9158. path `gawk' will use.
  9159.  
  9160.    ---------- Footnotes ----------
  9161.  
  9162.    (1)  Your version of `gawk' may use a directory that is different
  9163. than `/usr/local/share/awk'; it will depend upon how `gawk' was built
  9164. and installed. The actual directory will be the value of `$(datadir)'
  9165. generated when `gawk' was configured.  You probably don't need to worry
  9166. about this though.
  9167.  
  9168. 
  9169. File: gawk.info,  Node: Obsolete,  Next: Undocumented,  Prev: AWKPATH Variable,  Up: Invoking Gawk
  9170.  
  9171. Obsolete Options and/or Features
  9172. ================================
  9173.  
  9174.    This section describes features and/or command line options from
  9175. previous releases of `gawk' that are either not available in the
  9176. current version, or that are still supported but deprecated (meaning
  9177. that they will *not* be in the next release).
  9178.  
  9179.    For version 3.0 of `gawk', there are no command line options or
  9180. other deprecated features from the previous version of `gawk'.  This
  9181. node is thus essentially a place holder, in case some option becomes
  9182. obsolete in a future version of `gawk'.
  9183.  
  9184. 
  9185. File: gawk.info,  Node: Undocumented,  Next: Known Bugs,  Prev: Obsolete,  Up: Invoking Gawk
  9186.  
  9187. Undocumented Options and Features
  9188. =================================
  9189.  
  9190.    This section intentionally left blank.
  9191.  
  9192. 
  9193. File: gawk.info,  Node: Known Bugs,  Prev: Undocumented,  Up: Invoking Gawk
  9194.  
  9195. Known Bugs in `gawk'
  9196. ====================
  9197.  
  9198.    * The `-F' option for changing the value of `FS' (*note Command Line
  9199.      Options: Options.) is not necessary given the command line variable
  9200.      assignment feature; it remains only for backwards compatibility.
  9201.  
  9202.    * If your system actually has support for `/dev/fd' and the
  9203.      associated `/dev/stdin', `/dev/stdout', and `/dev/stderr' files,
  9204.      you may get different output from `gawk' than you would get on a
  9205.      system without those files.  When `gawk' interprets these files
  9206.      internally, it synchronizes output to the standard output with
  9207.      output to `/dev/stdout', while on a system with those files, the
  9208.      output is actually to different open files (*note Special File
  9209.      Names in `gawk': Special Files.).
  9210.  
  9211.    * Syntactically invalid single character programs tend to overflow
  9212.      the parse stack, generating a rather unhelpful message.  Such
  9213.      programs are surprisingly difficult to diagnose in the completely
  9214.      general case, and the effort to do so really is not worth it.
  9215.  
  9216.    * The word "GNU" is incorrectly capitalized in at least one file in
  9217.      the source code.
  9218.  
  9219. 
  9220. File: gawk.info,  Node: Library Functions,  Next: Sample Programs,  Prev: Invoking Gawk,  Up: Top
  9221.  
  9222. A Library of `awk' Functions
  9223. ****************************
  9224.  
  9225.    This chapter presents a library of useful `awk' functions.  The
  9226. sample programs presented later (*note Practical `awk' Programs: Sample
  9227. Programs.) use these functions.  The functions are presented here in a
  9228. progression from simple to complex.
  9229.  
  9230.    *Note Extracting Programs from Texinfo Source Files: Extract Program,
  9231. presents a program that you can use to extract the source code for
  9232. these example library functions and programs from the Texinfo source
  9233. for this Info file.  (This has already been done as part of the `gawk'
  9234. distribution.)
  9235.  
  9236.    If you have written one or more useful, general purpose `awk'
  9237. functions, and would like to contribute them for a subsequent edition
  9238. of this Info file, please contact the author.  *Note Reporting Problems
  9239. and Bugs: Bugs, for information on doing this.  Don't just send code,
  9240. as you will be required to either place your code in the public domain,
  9241. publish it under the GPL (*note GNU GENERAL PUBLIC LICENSE: Copying.),
  9242. or assign the copyright in it to the Free Software Foundation.
  9243.  
  9244. * Menu:
  9245.  
  9246. * Portability Notes::           What to do if you don't have `gawk'.
  9247. * Nextfile Function::           Two implementations of a `nextfile'
  9248.                                 function.
  9249. * Assert Function::             A function for assertions in `awk'
  9250.                                 programs.
  9251. * Ordinal Functions::           Functions for using characters as numbers and
  9252.                                 vice versa.
  9253. * Join Function::               A function to join an array into a string.
  9254. * Mktime Function::             A function to turn a date into a timestamp.
  9255. * Gettimeofday Function::       A function to get formatted times.
  9256. * Filetrans Function::          A function for handling data file transitions.
  9257. * Getopt Function::             A function for processing command line
  9258.                                 arguments.
  9259. * Passwd Functions::            Functions for getting user information.
  9260. * Group Functions::             Functions for getting group information.
  9261. * Library Names::               How to best name private global variables in
  9262.                                 library functions.
  9263.  
  9264. 
  9265. File: gawk.info,  Node: Portability Notes,  Next: Nextfile Function,  Prev: Library Functions,  Up: Library Functions
  9266.  
  9267. Simulating `gawk'-specific Features
  9268. ===================================
  9269.  
  9270.    The programs in this chapter and in *Note Practical `awk' Programs:
  9271. Sample Programs, freely use features that are specific to `gawk'.  This
  9272. section briefly discusses how you can rewrite these programs for
  9273. different implementations of `awk'.
  9274.  
  9275.    Diagnostic error messages are sent to `/dev/stderr'.  Use `| "cat
  9276. 1>&2"' instead of `> "/dev/stderr"', if your system does not have a
  9277. `/dev/stderr', or if you cannot use `gawk'.
  9278.  
  9279.    A number of programs use `nextfile' (*note The `nextfile' Statement:
  9280. Nextfile Statement.), to skip any remaining input in the input file.
  9281. *Note Implementing `nextfile' as a Function: Nextfile Function, shows
  9282. you how to write a function that will do the same thing.
  9283.  
  9284.    Finally, some of the programs choose to ignore upper-case and
  9285. lower-case distinctions in their input. They do this by assigning one
  9286. to `IGNORECASE'.  You can achieve the same effect by adding the
  9287. following rule to the beginning of the program:
  9288.  
  9289.      # ignore case
  9290.      { $0 = tolower($0) }
  9291.  
  9292. Also, verify that all regexp and string constants used in comparisons
  9293. only use lower-case letters.
  9294.  
  9295. 
  9296. File: gawk.info,  Node: Nextfile Function,  Next: Assert Function,  Prev: Portability Notes,  Up: Library Functions
  9297.  
  9298. Implementing `nextfile' as a Function
  9299. =====================================
  9300.  
  9301.    The `nextfile' statement presented in *Note The `nextfile'
  9302. Statement: Nextfile Statement, is a `gawk'-specific extension.  It is
  9303. not available in other implementations of `awk'.  This section shows
  9304. two versions of a `nextfile' function that you can use to simulate
  9305. `gawk''s `nextfile' statement if you cannot use `gawk'.
  9306.  
  9307.    Here is a first attempt at writing a `nextfile' function.
  9308.  
  9309.      # nextfile --- skip remaining records in current file
  9310.      
  9311.      # this should be read in before the "main" awk program
  9312.      
  9313.      function nextfile()    { _abandon_ = FILENAME; next }
  9314.      
  9315.      _abandon_ == FILENAME  { next }
  9316.  
  9317.    This file should be included before the main program, because it
  9318. supplies a rule that must be executed first.  This rule compares the
  9319. current data file's name (which is always in the `FILENAME' variable)
  9320. to a private variable named `_abandon_'.  If the file name matches,
  9321. then the action part of the rule executes a `next' statement, to go on
  9322. to the next record.  (The use of `_' in the variable name is a
  9323. convention.  It is discussed more fully in *Note Naming Library
  9324. Function Global Variables: Library Names.)
  9325.  
  9326.    The use of the `next' statement effectively creates a loop that reads
  9327. all the records from the current data file.  Eventually, the end of the
  9328. file is reached, and a new data file is opened, changing the value of
  9329. `FILENAME'.  Once this happens, the comparison of `_abandon_' to
  9330. `FILENAME' fails, and execution continues with the first rule of the
  9331. "real" program.
  9332.  
  9333.    The `nextfile' function itself simply sets the value of `_abandon_'
  9334. and then executes a `next' statement to start the loop going.(1)
  9335.  
  9336.    This initial version has a subtle problem.  What happens if the same
  9337. data file is listed *twice* on the command line, one right after the
  9338. other, or even with just a variable assignment between the two
  9339. occurrences of the file name?
  9340.  
  9341.    In such a case, this code will skip right through the file, a second
  9342. time, even though it should stop when it gets to the end of the first
  9343. occurrence.  Here is a second version of `nextfile' that remedies this
  9344. problem.
  9345.  
  9346.      # nextfile --- skip remaining records in current file
  9347.      # correctly handle successive occurrences of the same file
  9348.      # Arnold Robbins, arnold@gnu.ai.mit.edu, Public Domain
  9349.      # May, 1993
  9350.      
  9351.      # this should be read in before the "main" awk program
  9352.      
  9353.      function nextfile()   { _abandon_ = FILENAME; next }
  9354.      
  9355.      _abandon_ == FILENAME {
  9356.            if (FNR == 1)
  9357.                _abandon_ = ""
  9358.            else
  9359.                next
  9360.      }
  9361.  
  9362.    The `nextfile' function has not changed.  It sets `_abandon_' equal
  9363. to the current file name and then executes a `next' satement.  The
  9364. `next' statement reads the next record and increments `FNR', so `FNR'
  9365. is guaranteed to have a value of at least two.  However, if `nextfile'
  9366. is called for the last record in the file, then `awk' will close the
  9367. current data file and move on to the next one.  Upon doing so,
  9368. `FILENAME' will be set to the name of the new file, and `FNR' will be
  9369. reset to one.  If this next file is the same as the previous one,
  9370. `_abandon_' will still be equal to `FILENAME'.  However, `FNR' will be
  9371. equal to one, telling us that this is a new occurrence of the file, and
  9372. not the one we were reading when the `nextfile' function was executed.
  9373. In that case, `_abandon_' is reset to the empty string, so that further
  9374. executions of this rule will fail (until the next time that `nextfile'
  9375. is called).
  9376.  
  9377.    If `FNR' is not one, then we are still in the original data file,
  9378. and the program executes a `next' statement to skip through it.
  9379.  
  9380.    An important question to ask at this point is: "Given that the
  9381. functionality of `nextfile' can be provided with a library file, why is
  9382. it built into `gawk'?"  This is an important question.  Adding features
  9383. for little reason leads to larger, slower programs that are harder to
  9384. maintain.
  9385.  
  9386.    The answer is that building `nextfile' into `gawk' provides
  9387. significant gains in efficiency.  If the `nextfile' function is executed
  9388. at the beginning of a large data file, `awk' still has to scan the
  9389. entire file, splitting it up into records, just to skip over it.  The
  9390. built-in `nextfile' can simply close the file immediately and proceed
  9391. to the next one, saving a lot of time.  This is particularly important
  9392. in `awk', since `awk' programs are generally I/O bound (i.e.  they
  9393. spend most of their time doing input and output, instead of performing
  9394. computations).
  9395.  
  9396.    ---------- Footnotes ----------
  9397.  
  9398.    (1)  Some implementations of `awk' do not allow you to execute
  9399. `next' from within a function body. Some other work-around will be
  9400. necessary if you use such a version.
  9401.  
  9402. 
  9403. File: gawk.info,  Node: Assert Function,  Next: Ordinal Functions,  Prev: Nextfile Function,  Up: Library Functions
  9404.  
  9405. Assertions
  9406. ==========
  9407.  
  9408.    When writing large programs, it is often useful to be able to know
  9409. that a condition or set of conditions is true.  Before proceeding with a
  9410. particular computation, you make a statement about what you believe to
  9411. be the case.  Such a statement is known as an "assertion."  The C
  9412. language provides an `<assert.h>' header file and corresponding
  9413. `assert' macro that the programmer can use to make assertions.  If an
  9414. assertion fails, the `assert' macro arranges to print a diagnostic
  9415. message describing the condition that should have been true but was
  9416. not, and then it kills the program.  In C, using `assert' looks this:
  9417.  
  9418.      #include <assert.h>
  9419.      
  9420.      int myfunc(int a, double b)
  9421.      {
  9422.           assert(a <= 5 && b >= 17);
  9423.           ...
  9424.      }
  9425.  
  9426.    If the assertion failed, the program would print a message similar to
  9427. this:
  9428.  
  9429.      prog.c:5: assertion failed: a <= 5 && b >= 17
  9430.  
  9431.    The ANSI C language makes it possible to turn the condition into a
  9432. string for use in printing the diagnostic message.  This is not
  9433. possible in `awk', so this `assert' function also requires a string
  9434. version of the condition that is being tested.
  9435.  
  9436.      # assert --- assert that a condition is true. Otherwise exit.
  9437.      # Arnold Robbins, arnold@gnu.ai.mit.edu, Public Domain
  9438.      # May, 1993
  9439.      
  9440.      function assert(condition, string)
  9441.      {
  9442.          if (! condition) {
  9443.              printf("%s:%d: assertion failed: %s\n",
  9444.                  FILENAME, FNR, string) > "/dev/stderr"
  9445.              _assert_exit = 1
  9446.              exit 1
  9447.          }
  9448.      }
  9449.      
  9450.      END {
  9451.          if (_assert_exit)
  9452.              exit 1
  9453.      }
  9454.  
  9455.    The `assert' function tests the `condition' parameter. If it is
  9456. false, it prints a message to standard error, using the `string'
  9457. parameter to describe the failed condition.  It then sets the variable
  9458. `_assert_exit' to one, and executes the `exit' statement.  The `exit'
  9459. statement jumps to the `END' rule. If the `END' rules finds
  9460. `_assert_exit' to be true, then it exits immediately.
  9461.  
  9462.    The purpose of the `END' rule with its test is to keep any other
  9463. `END' rules from running.  When an assertion fails, the program should
  9464. exit immediately.  If no assertions fail, then `_assert_exit' will
  9465. still be false when the `END' rule is run normally, and the rest of the
  9466. program's `END' rules will execute.  For all of this to work correctly,
  9467. `assert.awk' must be the first source file read by `awk'.
  9468.  
  9469.    You would use this function in your programs this way:
  9470.  
  9471.      function myfunc(a, b)
  9472.      {
  9473.           assert(a <= 5 && b >= 17, "a <= 5 && b >= 17")
  9474.           ...
  9475.      }
  9476.  
  9477. If the assertion failed, you would see a message like this:
  9478.  
  9479.      mydata:1357: assertion failed: a <= 5 && b >= 17
  9480.  
  9481.    There is a problem with this version of `assert', that it may not be
  9482. possible to work around.  An `END' rule is automatically added to the
  9483. program calling `assert'.  Normally, if a program consists of just a
  9484. `BEGIN' rule, the input files and/or standard input are not read.
  9485. However, now that the program has an `END' rule, `awk' will attempt to
  9486. read the input data files, or standard input (*note Startup and Cleanup
  9487. Actions: Using BEGIN/END.), most likely causing the program to hang,
  9488. waiting for input.
  9489.  
  9490.    Just a note on programming style. You may have noticed that the `END'
  9491. rule uses backslash continuation, with the open brace on a line by
  9492. itself.  This is so that it more closely resembles the way functions
  9493. are written.  Many of the examples use this style. You can decide for
  9494. yourself if you like writing your `BEGIN' and `END' rules this way, or
  9495. not.
  9496.  
  9497. 
  9498. File: gawk.info,  Node: Ordinal Functions,  Next: Join Function,  Prev: Assert Function,  Up: Library Functions
  9499.  
  9500. Translating Between Characters and Numbers
  9501. ==========================================
  9502.  
  9503.    One commercial implementation of `awk' supplies a built-in function,
  9504. `ord', which takes a character and returns the numeric value for that
  9505. character in the machine's character set.  If the string passed to
  9506. `ord' has more than one character, only the first one is used.
  9507.  
  9508.    The inverse of this function is `chr' (from the function of the same
  9509. name in Pascal), which takes a number and returns the corresponding
  9510. character.
  9511.  
  9512.    Both functions can be written very nicely in `awk'; there is no real
  9513. reason to build them into the `awk' interpreter.
  9514.  
  9515.      # ord.awk --- do ord and chr
  9516.      #
  9517.      # Global identifiers:
  9518.      #    _ord_:        numerical values indexed by characters
  9519.      #    _ord_init:    function to initialize _ord_
  9520.      #
  9521.      # Arnold Robbins
  9522.      # arnold@gnu.ai.mit.edu
  9523.      # Public Domain
  9524.      # 16 January, 1992
  9525.      # 20 July, 1992, revised
  9526.      
  9527.      BEGIN    { _ord_init() }
  9528.      
  9529.      function _ord_init(    low, high, i, t)
  9530.      {
  9531.          low = sprintf("%c", 7) # BEL is ascii 7
  9532.          if (low == "\a") {    # regular ascii
  9533.              low = 0
  9534.              high = 127
  9535.          } else if (sprintf("%c", 128 + 7) == "\a") {
  9536.              # ascii, mark parity
  9537.              low = 128
  9538.              high = 255
  9539.          } else {        # ebcdic(!)
  9540.              low = 0
  9541.              high = 255
  9542.          }
  9543.      
  9544.          for (i = low; i <= high; i++) {
  9545.              t = sprintf("%c", i)
  9546.              _ord_[t] = i
  9547.          }
  9548.      }
  9549.  
  9550.    Some explanation of the numbers used by `chr' is worthwhile.  The
  9551. most prominent character set in use today is ASCII. Although an
  9552. eight-bit byte can hold 256 distinct values (from zero to 255), ASCII
  9553. only defines characters that use the values from zero to 127.(1) At
  9554. least one computer manufacturer that we know of uses ASCII, but with
  9555. mark parity, meaning that the leftmost bit in the byte is always one.
  9556. What this means is that on those systems, characters have numeric
  9557. values from 128 to 255.  Finally, large mainframe systems use the
  9558. EBCDIC character set, which uses all 256 values.  While there are other
  9559. character sets in use on some older systems, they are not really worth
  9560. worrying about.
  9561.  
  9562.      function ord(str,    c)
  9563.      {
  9564.          # only first character is of interest
  9565.          c = substr(str, 1, 1)
  9566.          return _ord_[c]
  9567.      }
  9568.      
  9569.      function chr(c)
  9570.      {
  9571.          # force c to be numeric by adding 0
  9572.          return sprintf("%c", c + 0)
  9573.      }
  9574.      
  9575.      #### test code ####
  9576.      # BEGIN    \
  9577.      # {
  9578.      #    for (;;) {
  9579.      #        printf("enter a character: ")
  9580.      #        if (getline var <= 0)
  9581.      #            break
  9582.      #        printf("ord(%s) = %d\n", var, ord(var))
  9583.      #    }
  9584.      # }
  9585.  
  9586.    An obvious improvement to these functions would be to move the code
  9587. for the `_ord_init' function into the body of the `BEGIN' rule.  It was
  9588. written this way initially for ease of development.
  9589.  
  9590.    There is a "test program" in a `BEGIN' rule, for testing the
  9591. function.  It is commented out for production use.
  9592.  
  9593.    ---------- Footnotes ----------
  9594.  
  9595.    (1)  ASCII has been extended in many countries to use the values
  9596. from 128 to 255 for country-specific characters.  If your  system uses
  9597. these extensions, you can simplify `_ord_init' to simply loop from zero
  9598. to 255.
  9599.  
  9600. 
  9601. File: gawk.info,  Node: Join Function,  Next: Mktime Function,  Prev: Ordinal Functions,  Up: Library Functions
  9602.  
  9603. Merging an Array Into a String
  9604. ==============================
  9605.  
  9606.    When doing string processing, it is often useful to be able to join
  9607. all the strings in an array into one long string.  The following
  9608. function, `join', accomplishes this task.  It is used later in several
  9609. of the application programs (*note Practical `awk' Programs: Sample
  9610. Programs.).
  9611.  
  9612.    Good function design is important; this function needs to be
  9613. general, but it should also have a reasonable default behavior.  It is
  9614. called with an array and the beginning and ending indices of the
  9615. elements in the array to be merged.  This assumes that the array
  9616. indices are numeric--a reasonable assumption since the array was likely
  9617. created with `split' (*note Built-in Functions for String Manipulation:
  9618. String Functions.).
  9619.  
  9620.      # join.awk --- join an array into a string
  9621.      # Arnold Robbins, arnold@gnu.ai.mit.edu, Public Domain
  9622.      # May 1993
  9623.      
  9624.      function join(array, start, end, sep,    result, i)
  9625.      {
  9626.          if (sep == "")
  9627.             sep = " "
  9628.          else if (sep == SUBSEP) # magic value
  9629.             sep = ""
  9630.          result = array[start]
  9631.          for (i = start + 1; i <= end; i++)
  9632.              result = result sep array[i]
  9633.          return result
  9634.      }
  9635.  
  9636.    An optional additional argument is the separator to use when joining
  9637. the strings back together.  If the caller supplies a non-empty value,
  9638. `join' uses it.  If it is not supplied, it will have a null value.  In
  9639. this case, `join' uses a single blank as a default separator for the
  9640. strings.  If the value is equal to `SUBSEP', then `join' joins the
  9641. strings with no separator between them.  `SUBSEP' serves as a "magic"
  9642. value to indicate that there should be no separation between the
  9643. component strings.
  9644.  
  9645.    It would be nice if `awk' had an assignment operator for
  9646. concatenation.  The lack of an explicit operator for concatenation
  9647. makes string operations more difficult than they really need to be.
  9648.  
  9649. 
  9650. File: gawk.info,  Node: Mktime Function,  Next: Gettimeofday Function,  Prev: Join Function,  Up: Library Functions
  9651.  
  9652. Turning Dates Into Timestamps
  9653. =============================
  9654.  
  9655.    The `systime' function built in to `gawk' returns the current time
  9656. of day as a timestamp in "seconds since the Epoch."  This timestamp can
  9657. be converted into a printable date of almost infinitely variable format
  9658. using the built-in `strftime' function.  (For more information on
  9659. `systime' and `strftime', *note Functions for Dealing with Time Stamps:
  9660. Time Functions..)
  9661.  
  9662.    An interesting but difficult problem is to convert a readable
  9663. representation of a date back into a timestamp.  The ANSI C library
  9664. provides a `mktime' function that does the basic job, converting a
  9665. canonical representation of a date into a timestamp.
  9666.  
  9667.    It would appear at first glance that `gawk' would have to supply a
  9668. `mktime' built-in function that was simply a "hook" to the C language
  9669. version.  In fact though, `mktime' can be implemented entirely in `awk'.
  9670.  
  9671.    Here is a version of `mktime' for `awk'.  It takes a simple
  9672. representation of the date and time, and converts it into a timestamp.
  9673.  
  9674.    The code is presented here intermixed with explanatory prose.  In
  9675. *Note Extracting Programs from Texinfo Source Files: Extract Program,
  9676. you will see how the Texinfo source file for this Info file can be
  9677. processed to extract the code into a single source file.
  9678.  
  9679.    The program begins with a descriptive comment and a `BEGIN' rule
  9680. that initializes a table `_tm_months'.  This table is a two-dimensional
  9681. array that has the lengths of the months.  The first index is zero for
  9682. regular years, and one for leap years.  The values are the same for all
  9683. the months in both kinds of years, except for February; thus the use of
  9684. multiple assignment.
  9685.  
  9686.      # mktime.awk --- convert a canonical date representation
  9687.      #                into a timestamp
  9688.      # Arnold Robbins, arnold@gnu.ai.mit.edu, Public Domain
  9689.      # May 1993
  9690.      
  9691.      BEGIN    \
  9692.      {
  9693.          # Initialize table of month lengths
  9694.          _tm_months[0,1] = _tm_months[1,1] = 31
  9695.          _tm_months[0,2] = 28; _tm_months[1,2] = 29
  9696.          _tm_months[0,3] = _tm_months[1,3] = 31
  9697.          _tm_months[0,4] = _tm_months[1,4] = 30
  9698.          _tm_months[0,5] = _tm_months[1,5] = 31
  9699.          _tm_months[0,6] = _tm_months[1,6] = 30
  9700.          _tm_months[0,7] = _tm_months[1,7] = 31
  9701.          _tm_months[0,8] = _tm_months[1,8] = 31
  9702.          _tm_months[0,9] = _tm_months[1,9] = 30
  9703.          _tm_months[0,10] = _tm_months[1,10] = 31
  9704.          _tm_months[0,11] = _tm_months[1,11] = 30
  9705.          _tm_months[0,12] = _tm_months[1,12] = 31
  9706.      }
  9707.  
  9708.    The benefit of merging multiple `BEGIN' rules (*note The `BEGIN' and
  9709. `END' Special Patterns: BEGIN/END.) is particularly clear when writing
  9710. library files.  Functions in library files can cleanly initialize their
  9711. own private data and also provide clean-up actions in private `END'
  9712. rules.
  9713.  
  9714.    The next function is a simple one that computes whether a given year
  9715. is or is not a leap year.  If a year is evenly divisible by four, but
  9716. not evenly divisible by 100, or if it is evenly divisible by 400, then
  9717. it is a leap year.  Thus, 1904 was a leap year, 1900 was not, but 2000
  9718. will be.
  9719.  
  9720.      # decide if a year is a leap year
  9721.      function _tm_isleap(year,    ret)
  9722.      {
  9723.          ret = (year % 4 == 0 && year % 100 != 0) ||
  9724.                  (year % 400 == 0)
  9725.      
  9726.          return ret
  9727.      }
  9728.  
  9729.    This function is only used a few times in this file, and its
  9730. computation could have been written "in-line" (at the point where it's
  9731. used).  Making it a separate function made the original development
  9732. easier, and also avoids the possibility of typing errors when
  9733. duplicating the code in multiple places.
  9734.  
  9735.    The next function is more interesting.  It does most of the work of
  9736. generating a timestamp, which is converting a date and time into some
  9737. number of seconds since the Epoch.  The caller passes an array (rather
  9738. imaginatively named `a') containing six values: the year including
  9739. century, the month as a number between one and 12, the day of the
  9740. month, the hour as a number between zero and 23, the minute in the
  9741. hour, and the seconds within the minute.
  9742.  
  9743.    The function uses several local variables to precompute the number of
  9744. seconds in an hour, seconds in a day, and seconds in a year.  Often,
  9745. similar C code simply writes out the expression in-line, expecting the
  9746. compiler to do "constant folding".  E.g., most C compilers would turn
  9747. `60 * 60' into `3600' at compile time, instead of recomputing it every
  9748. time at run time.  Precomputing these values makes the function more
  9749. efficient.
  9750.  
  9751.      # convert a date into seconds
  9752.      function _tm_addup(a,    total, yearsecs, daysecs,
  9753.                               hoursecs, i, j)
  9754.      {
  9755.          hoursecs = 60 * 60
  9756.          daysecs = 24 * hoursecs
  9757.          yearsecs = 365 * daysecs
  9758.      
  9759.          total = (a[1] - 1970) * yearsecs
  9760.      
  9761.          # extra day for leap years
  9762.          for (i = 1970; i < a[1]; i++)
  9763.              if (_tm_isleap(i))
  9764.                  total += daysecs
  9765.      
  9766.          j = _tm_isleap(a[1])
  9767.          for (i = 1; i < a[2]; i++)
  9768.              total += _tm_months[j, i] * daysecs
  9769.      
  9770.          total += (a[3] - 1) * daysecs
  9771.          total += a[4] * hoursecs
  9772.          total += a[5] * 60
  9773.          total += a[6]
  9774.      
  9775.          return total
  9776.      }
  9777.  
  9778.    The function starts with a first approximation of all the seconds
  9779. between Midnight, January 1, 1970,(1) and the beginning of the current
  9780. year.  It then goes through all those years, and for every leap year,
  9781. adds an additional day's worth of seconds.
  9782.  
  9783.    The variable `j' holds either one or zero, if the current year is or
  9784. is not a leap year.  For every month in the current year prior to the
  9785. current month, it adds the number of seconds in the month, using the
  9786. appropriate entry in the `_tm_months' array.
  9787.  
  9788.    Finally, it adds in the seconds for the number of days prior to the
  9789. current day, and the number of hours, minutes, and seconds in the
  9790. current day.
  9791.  
  9792.    The result is a count of seconds since January 1, 1970.  This value
  9793. is not yet what is needed though.  The reason why is described shortly.
  9794.  
  9795.    The main `mktime' function takes a single character string argument.
  9796. This string is a representation of a date and time in a "canonical"
  9797. (fixed) form.  This string should be `"YEAR MONTH DAY HOUR MINUTE
  9798. SECOND"'.
  9799.  
  9800.      # mktime --- convert a date into seconds,
  9801.      #            compensate for time zone
  9802.      
  9803.      function mktime(str,    res1, res2, a, b, i, j, t, diff)
  9804.      {
  9805.          i = split(str, a, " ")    # don't rely on FS
  9806.      
  9807.          if (i != 6)
  9808.              return -1
  9809.      
  9810.          # force numeric
  9811.          for (j in a)
  9812.              a[j] += 0
  9813.      
  9814.          # validate
  9815.          if (a[1] < 1970 ||
  9816.              a[2] < 1 || a[2] > 12 ||
  9817.              a[3] < 1 || a[3] > 31 ||
  9818.              a[4] < 0 || a[4] > 23 ||
  9819.              a[5] < 0 || a[5] > 59 ||
  9820.              a[6] < 0 || a[6] > 61 )
  9821.                  return -1
  9822.      
  9823.          res1 = _tm_addup(a)
  9824.          t = strftime("%Y %m %d %H %M %S", res1)
  9825.      
  9826.          if (_tm_debug)
  9827.              printf("(%s) -> (%s)\n", str, t) > "/dev/stderr"
  9828.      
  9829.          split(t, b, " ")
  9830.          res2 = _tm_addup(b)
  9831.      
  9832.          diff = res1 - res2
  9833.      
  9834.          if (_tm_debug)
  9835.              printf("diff = %d seconds\n", diff) > "/dev/stderr"
  9836.      
  9837.          res1 += diff
  9838.      
  9839.          return res1
  9840.      }
  9841.  
  9842.    The function first splits the string into an array, using spaces and
  9843. tabs as separators.  If there are not six elements in the array, it
  9844. returns an error, signaled as the value -1.  Next, it forces each
  9845. element of the array to be numeric, by adding zero to it.  The
  9846. following `if' statement then makes sure that each element is within an
  9847. allowable range.  (This checking could be extended further, e.g., to
  9848. make sure that the day of the month is within the correct range for the
  9849. particular month supplied.)  All of this is essentially preliminary
  9850. set-up and error checking.
  9851.  
  9852.    Recall that `_tm_addup' generated a value in seconds since Midnight,
  9853. January 1, 1970.  This value is not directly usable as the result we
  9854. want, *since the calculation does not account for the local timezone*.
  9855. In other words, the value represents the count in seconds since the
  9856. Epoch, but only for UTC (Universal Coordinated Time).  If the local
  9857. timezone is east or west of UTC, then some number of hours should be
  9858. either added to, or subtracted from the resulting timestamp.
  9859.  
  9860.    For example, 6:23 p.m. in Atlanta, Georgia (USA), is normally five
  9861. hours west of (behind) UTC.  It is only four hours behind UTC if
  9862. daylight savings time is in effect.  If you are calling `mktime' in
  9863. Atlanta, with the argument `"1993 5 23 18 23 12"', the result from
  9864. `_tm_addup' will be for 6:23 p.m. UTC, which is only 2:23 p.m. in
  9865. Atlanta.  It is necessary to add another four hours worth of seconds to
  9866. the result.
  9867.  
  9868.    How can `mktime' determine how far away it is from UTC?  This is
  9869. surprisingly easy.  The returned timestamp represents the time passed to
  9870. `mktime' *as UTC*.  This timestamp can be fed back to `strftime', which
  9871. will format it as a *local* time; i.e. as if it already had the UTC
  9872. difference added in to it.  This is done by giving
  9873. `"%Y %m %d %H %M %S"' to `strftime' as the format argument.  It returns
  9874. the computed timestamp in the original string format.  The result
  9875. represents a time that accounts for the UTC difference.  When the new
  9876. time is converted back to a timestamp, the difference between the two
  9877. timestamps is the difference (in seconds) between the local timezone
  9878. and UTC.  This difference is then added back to the original result.
  9879. An example demonstrating this is presented below.
  9880.  
  9881.    Finally, there is a "main" program for testing the function.
  9882.  
  9883.      BEGIN  {
  9884.          if (_tm_test) {
  9885.              printf "Enter date as yyyy mm dd hh mm ss: "
  9886.              getline _tm_test_date
  9887.      
  9888.              t = mktime(_tm_test_date)
  9889.              r = strftime("%Y %m %d %H %M %S", t)
  9890.              printf "Got back (%s)\n", r
  9891.          }
  9892.      }
  9893.  
  9894.    The entire program uses two variables that can be set on the command
  9895. line to control debugging output and to enable the test in the final
  9896. `BEGIN' rule.  Here is the result of a test run. (Note that debugging
  9897. output is to standard error, and test output is to standard output.)
  9898.  
  9899.      $ gawk -f mktime.awk -v _tm_test=1 -v _tm_debug=1
  9900.      -| Enter date as yyyy mm dd hh mm ss: 1993 5 23 15 35 10
  9901.      error--> (1993 5 23 15 35 10) -> (1993 05 23 11 35 10)
  9902.      error--> diff = 14400 seconds
  9903.      -| Got back (1993 05 23 15 35 10)
  9904.  
  9905.    The time entered was 3:35 p.m. (15:35 on a 24-hour clock), on May
  9906. 23, 1993.  The first line of debugging output shows the resulting time
  9907. as UTC--four hours ahead of the local time zone.  The second line shows
  9908. that the difference is 14400 seconds, which is four hours.  (The
  9909. difference is only four hours, since daylight savings time is in effect
  9910. during May.) The final line of test output shows that the timezone
  9911. compensation algorithm works; the returned time is the same as the
  9912. entered time.
  9913.  
  9914.    This program does not solve the general problem of turning an
  9915. arbitrary date representation into a timestamp.  That problem is very
  9916. involved.  However, the `mktime' function provides a foundation upon
  9917. which to build. Other software can convert month names into numeric
  9918. months, and AM/PM times into 24-hour clocks, to generate the
  9919. "canonical" format that `mktime' requires.
  9920.  
  9921.    ---------- Footnotes ----------
  9922.  
  9923.    (1)  This is the Epoch on POSIX systems.  It may be different on
  9924. other systems.
  9925.  
  9926. 
  9927. File: gawk.info,  Node: Gettimeofday Function,  Next: Filetrans Function,  Prev: Mktime Function,  Up: Library Functions
  9928.  
  9929. Managing the Time of Day
  9930. ========================
  9931.  
  9932.    The `systime' and `strftime' functions described in *Note Functions
  9933. for Dealing with Time Stamps: Time Functions, provide the minimum
  9934. functionality necessary for dealing with the time of day in human
  9935. readable form.  While `strftime' is extensive, the control formats are
  9936. not necessarily easy to remember or intuitively obvious when reading a
  9937. program.
  9938.  
  9939.    The following function, `gettimeofday', populates a user-supplied
  9940. array with pre-formatted time information.  It returns a string with
  9941. the current time formatted in the same way as the `date' utility.
  9942.  
  9943.      # gettimeofday --- get the time of day in a usable format
  9944.      # Arnold Robbins, arnold@gnu.ai.mit.edu, Public Domain, May 1993
  9945.      #
  9946.      # Returns a string in the format of output of date(1)
  9947.      # Populates the array argument time with individual values:
  9948.      #    time["second"]       -- seconds (0 - 59)
  9949.      #    time["minute"]       -- minutes (0 - 59)
  9950.      #    time["hour"]         -- hours (0 - 23)
  9951.      #    time["althour"]      -- hours (0 - 12)
  9952.      #    time["monthday"]     -- day of month (1 - 31)
  9953.      #    time["month"]        -- month of year (1 - 12)
  9954.      #    time["monthname"]    -- name of the month
  9955.      #    time["shortmonth"]   -- short name of the month
  9956.      #    time["year"]         -- year within century (0 - 99)
  9957.      #    time["fullyear"]     -- year with century (19xx or 20xx)
  9958.      #    time["weekday"]      -- day of week (Sunday = 0)
  9959.      #    time["altweekday"]   -- day of week (Monday = 0)
  9960.      #    time["weeknum"]      -- week number, Sunday first day
  9961.      #    time["altweeknum"]   -- week number, Monday first day
  9962.      #    time["dayname"]      -- name of weekday
  9963.      #    time["shortdayname"] -- short name of weekday
  9964.      #    time["yearday"]      -- day of year (0 - 365)
  9965.      #    time["timezone"]     -- abbreviation of timezone name
  9966.      #    time["ampm"]         -- AM or PM designation
  9967.      
  9968.      function gettimeofday(time,    ret, now, i)
  9969.      {
  9970.          # get time once, avoids unnecessary system calls
  9971.          now = systime()
  9972.      
  9973.          # return date(1)-style output
  9974.          ret = strftime("%a %b %d %H:%M:%S %Z %Y", now)
  9975.      
  9976.          # clear out target array
  9977.          for (i in time)
  9978.              delete time[i]
  9979.      
  9980.          # fill in values, force numeric values to be
  9981.          # numeric by adding 0
  9982.          time["second"]       = strftime("%S", now) + 0
  9983.          time["minute"]       = strftime("%M", now) + 0
  9984.          time["hour"]         = strftime("%H", now) + 0
  9985.          time["althour"]      = strftime("%I", now) + 0
  9986.          time["monthday"]     = strftime("%d", now) + 0
  9987.          time["month"]        = strftime("%m", now) + 0
  9988.          time["monthname"]    = strftime("%B", now)
  9989.          time["shortmonth"]   = strftime("%b", now)
  9990.          time["year"]         = strftime("%y", now) + 0
  9991.          time["fullyear"]     = strftime("%Y", now) + 0
  9992.          time["weekday"]      = strftime("%w", now) + 0
  9993.          time["altweekday"]   = strftime("%u", now) + 0
  9994.          time["dayname"]      = strftime("%A", now)
  9995.          time["shortdayname"] = strftime("%a", now)
  9996.          time["yearday"]      = strftime("%j", now) + 0
  9997.          time["timezone"]     = strftime("%Z", now)
  9998.          time["ampm"]         = strftime("%p", now)
  9999.          time["weeknum"]      = strftime("%U", now) + 0
  10000.          time["altweeknum"]   = strftime("%W", now) + 0
  10001.      
  10002.          return ret
  10003.      }
  10004.  
  10005.    The string indices are easier to use and read than the various
  10006. formats required by `strftime'.  The `alarm' program presented in *Note
  10007. An Alarm Clock Program: Alarm Program, uses this function.
  10008.  
  10009.    The `gettimeofday' function is presented above as it was written. A
  10010. more general design for this function would have allowed the user to
  10011. supply an optional timestamp value that would have been used instead of
  10012. the current time.
  10013.  
  10014. 
  10015. File: gawk.info,  Node: Filetrans Function,  Next: Getopt Function,  Prev: Gettimeofday Function,  Up: Library Functions
  10016.  
  10017. Noting Data File Boundaries
  10018. ===========================
  10019.  
  10020.    The `BEGIN' and `END' rules are each executed exactly once, at the
  10021. beginning and end respectively of your `awk' program (*note The `BEGIN'
  10022. and `END' Special Patterns: BEGIN/END.).  We (the `gawk' authors) once
  10023. had a user who mistakenly thought that the `BEGIN' rule was executed at
  10024. the beginning of each data file and the `END' rule was executed at the
  10025. end of each data file.  When informed that this was not the case, the
  10026. user requested that we add new special patterns to `gawk', named
  10027. `BEGIN_FILE' and `END_FILE', that would have the desired behavior.  He
  10028. even supplied us the code to do so.
  10029.  
  10030.    However, after a little thought, I came up with the following
  10031. library program.  It arranges to call two user-supplied functions,
  10032. `beginfile' and `endfile', at the beginning and end of each data file.
  10033. Besides solving the problem in only nine(!) lines of code, it does so
  10034. *portably*; this will work with any implementation of `awk'.
  10035.  
  10036.      # transfile.awk
  10037.      #
  10038.      # Give the user a hook for filename transitions
  10039.      #
  10040.      # The user must supply functions beginfile() and endfile()
  10041.      # that each take the name of the file being started or
  10042.      # finished, respectively.
  10043.      #
  10044.      # Arnold Robbins, arnold@gnu.ai.mit.edu, January 1992
  10045.      # Public Domain
  10046.      
  10047.      FILENAME != _oldfilename \
  10048.      {
  10049.          if (_oldfilename != "")
  10050.              endfile(_oldfilename)
  10051.          _oldfilename = FILENAME
  10052.          beginfile(FILENAME)
  10053.      }
  10054.      
  10055.      END   { endfile(FILENAME) }
  10056.  
  10057.    This file must be loaded before the user's "main" program, so that
  10058. the rule it supplies will be executed first.
  10059.  
  10060.    This rule relies on `awk''s `FILENAME' variable that automatically
  10061. changes for each new data file.  The current file name is saved in a
  10062. private variable, `_oldfilename'.  If `FILENAME' does not equal
  10063. `_oldfilename', then a new data file is being processed, and it is
  10064. necessary to call `endfile' for the old file.  Since `endfile' should
  10065. only be called if a file has been processed, the program first checks
  10066. to make sure that `_oldfilename' is not the null string.  The program
  10067. then assigns the current file name to `_oldfilename', and calls
  10068. `beginfile' for the file.  Since, like all `awk' variables,
  10069. `_oldfilename' will be initialized to the null string, this rule
  10070. executes correctly even for the first data file.
  10071.  
  10072.    The program also supplies an `END' rule, to do the final processing
  10073. for the last file.  Since this `END' rule comes before any `END' rules
  10074. supplied in the "main" program, `endfile' will be called first.  Once
  10075. again the value of multiple `BEGIN' and `END' rules should be clear.
  10076.  
  10077.    This version has same problem as the first version of `nextfile'
  10078. (*note Implementing `nextfile' as a Function: Nextfile Function.).  If
  10079. the same data file occurs twice in a row on command line, then
  10080. `endfile' and `beginfile' will not be executed at the end of the first
  10081. pass and at the beginning of the second pass.  This version solves the
  10082. problem.
  10083.  
  10084.      # ftrans.awk --- handle data file transitions
  10085.      #
  10086.      # user supplies beginfile() and endfile() functions
  10087.      #
  10088.      # Arnold Robbins, arnold@gnu.ai.mit.edu. November 1992
  10089.      # Public Domain
  10090.      
  10091.      FNR == 1 {
  10092.          if (_filename_ != "")
  10093.              endfile(_filename_)
  10094.          _filename_ = FILENAME
  10095.          beginfile(FILENAME)
  10096.      }
  10097.      
  10098.      END  { endfile(_filename_) }
  10099.  
  10100.    In *Note Counting Things: Wc Program, you will see how this library
  10101. function can be used, and how it simplifies writing the main program.
  10102.  
  10103. 
  10104. File: gawk.info,  Node: Getopt Function,  Next: Passwd Functions,  Prev: Filetrans Function,  Up: Library Functions
  10105.  
  10106. Processing Command Line Options
  10107. ===============================
  10108.  
  10109.    Most utilities on POSIX compatible systems take options or
  10110. "switches" on the command line that can be used to change the way a
  10111. program behaves.  `awk' is an example of such a program (*note Command
  10112. Line Options: Options.).  Often, options take "arguments", data that
  10113. the program needs to correctly obey the command line option.  For
  10114. example, `awk''s `-F' option requires a string to use as the field
  10115. separator.  The first occurrence on the command line of either `--' or a
  10116. string that does not begin with `-' ends the options.
  10117.  
  10118.    Most Unix systems provide a C function named `getopt' for processing
  10119. command line arguments.  The programmer provides a string describing
  10120. the one letter options. If an option requires an argument, it is
  10121. followed in the string with a colon.  `getopt' is also passed the count
  10122. and values of the command line arguments, and is called in a loop.
  10123. `getopt' processes the command line arguments for option letters.  Each
  10124. time around the loop, it returns a single character representing the
  10125. next option letter that it found, or `?' if it found an invalid option.
  10126. When it returns -1, there are no options left on the command line.
  10127.  
  10128.    When using `getopt', options that do not take arguments can be
  10129. grouped together.  Furthermore, options that take arguments require
  10130. that the argument be present.  The argument can immediately follow the
  10131. option letter, or it can be a separate command line argument.
  10132.  
  10133.    Given a hypothetical program that takes three command line options,
  10134. `-a', `-b', and `-c', and `-b' requires an argument, all of the
  10135. following are valid ways of invoking the program:
  10136.  
  10137.      prog -a -b foo -c data1 data2 data3
  10138.      prog -ac -bfoo -- data1 data2 data3
  10139.      prog -acbfoo data1 data2 data3
  10140.  
  10141.    Notice that when the argument is grouped with its option, the rest of
  10142. the command line argument is considered to be the option's argument.
  10143. In the above example, `-acbfoo' indicates that all of the `-a', `-b',
  10144. and `-c' options were supplied, and that `foo' is the argument to the
  10145. `-b' option.
  10146.  
  10147.    `getopt' provides four external variables that the programmer can
  10148. use.
  10149.  
  10150. `optind'
  10151.      The index in the argument value array (`argv') where the first
  10152.      non-option command line argument can be found.
  10153.  
  10154. `optarg'
  10155.      The string value of the argument to an option.
  10156.  
  10157. `opterr'
  10158.      Usually `getopt' prints an error message when it finds an invalid
  10159.      option.  Setting `opterr' to zero disables this feature.  (An
  10160.      application might wish to print its own error message.)
  10161.  
  10162. `optopt'
  10163.      The letter representing the command line option.  While not
  10164.      usually documented, most versions supply this variable.
  10165.  
  10166.    The following C fragment shows how `getopt' might process command
  10167. line arguments for `awk'.
  10168.  
  10169.      int
  10170.      main(int argc, char *argv[])
  10171.      {
  10172.          ...
  10173.          /* print our own message */
  10174.          opterr = 0;
  10175.          while ((c = getopt(argc, argv, "v:f:F:W:")) != -1) {
  10176.              switch (c) {
  10177.              case 'f':    /* file */
  10178.                  ...
  10179.                  break;
  10180.              case 'F':    /* field separator */
  10181.                  ...
  10182.                  break;
  10183.              case 'v':    /* variable assignment */
  10184.                  ...
  10185.                  break;
  10186.              case 'W':    /* extension */
  10187.                  ...
  10188.                  break;
  10189.              case '?':
  10190.              default:
  10191.                  usage();
  10192.                  break;
  10193.              }
  10194.          }
  10195.          ...
  10196.      }
  10197.  
  10198.    As a side point, `gawk' actually uses the GNU `getopt_long' function
  10199. to process both normal and GNU-style long options (*note Command Line
  10200. Options: Options.).
  10201.  
  10202.    The abstraction provided by `getopt' is very useful, and would be
  10203. quite handy in `awk' programs as well.  Here is an `awk' version of
  10204. `getopt'.  This function highlights one of the greatest weaknesses in
  10205. `awk', which is that it is very poor at manipulating single characters.
  10206. Repeated calls to `substr' are necessary for accessing individual
  10207. characters (*note Built-in Functions for String Manipulation: String
  10208. Functions.).
  10209.  
  10210.    The discussion walks through the code a bit at a time.
  10211.  
  10212.      # getopt --- do C library getopt(3) function in awk
  10213.      #
  10214.      # arnold@gnu.ai.mit.edu
  10215.      # Public domain
  10216.      #
  10217.      # Initial version: March, 1991
  10218.      # Revised: May, 1993
  10219.      
  10220.      # External variables:
  10221.      #    Optind -- index of ARGV for first non-option argument
  10222.      #    Optarg -- string value of argument to current option
  10223.      #    Opterr -- if non-zero, print our own diagnostic
  10224.      #    Optopt -- current option letter
  10225.      
  10226.      # Returns
  10227.      #    -1     at end of options
  10228.      #    ?      for unrecognized option
  10229.      #    <c>    a character representing the current option
  10230.      
  10231.      # Private Data
  10232.      #    _opti  index in multi-flag option, e.g., -abc
  10233.  
  10234.    The function starts out with some documentation: who wrote the code,
  10235. and when it was revised, followed by a list of the global variables it
  10236. uses, what the return values are and what they mean, and any global
  10237. variables that are "private" to this library function.  Such
  10238. documentation is essential for any program, and particularly for
  10239. library functions.
  10240.  
  10241.      function getopt(argc, argv, options,    optl, thisopt, i)
  10242.      {
  10243.          optl = length(options)
  10244.          if (optl == 0)        # no options given
  10245.              return -1
  10246.      
  10247.          if (argv[Optind] == "--") {  # all done
  10248.              Optind++
  10249.              _opti = 0
  10250.              return -1
  10251.          } else if (argv[Optind] !~ /^-[^: \t\n\f\r\v\b]/) {
  10252.              _opti = 0
  10253.              return -1
  10254.          }
  10255.  
  10256.    The function first checks that it was indeed called with a string of
  10257. options (the `options' parameter).  If `options' has a zero length,
  10258. `getopt' immediately returns -1.
  10259.  
  10260.    The next thing to check for is the end of the options.  A `--' ends
  10261. the command line options, as does any command line argument that does
  10262. not begin with a `-'.  `Optind' is used to step through the array of
  10263. command line arguments; it retains its value across calls to `getopt',
  10264. since it is a global variable.
  10265.  
  10266.    The regexp used, `/^-[^: \t\n\f\r\v\b]/', is perhaps a bit of
  10267. overkill; it checks for a `-' followed by anything that is not
  10268. whitespace and not a colon.  If the current command line argument does
  10269. not match this pattern, it is not an option, and it ends option
  10270. processing.
  10271.  
  10272.          if (_opti == 0)
  10273.              _opti = 2
  10274.          thisopt = substr(argv[Optind], _opti, 1)
  10275.          Optopt = thisopt
  10276.          i = index(options, thisopt)
  10277.          if (i == 0) {
  10278.              if (Opterr)
  10279.                  printf("%c -- invalid option\n",
  10280.                                        thisopt) > "/dev/stderr"
  10281.              if (_opti >= length(argv[Optind])) {
  10282.                  Optind++
  10283.                  _opti = 0
  10284.              } else
  10285.                  _opti++
  10286.              return "?"
  10287.          }
  10288.  
  10289.    The `_opti' variable tracks the position in the current command line
  10290. argument (`argv[Optind]').  In the case that multiple options were
  10291. grouped together with one `-' (e.g., `-abx'), it is necessary to return
  10292. them to the user one at a time.
  10293.  
  10294.    If `_opti' is equal to zero, it is set to two, the index in the
  10295. string of the next character to look at (we skip the `-', which is at
  10296. position one).  The variable `thisopt' holds the character, obtained
  10297. with `substr'.  It is saved in `Optopt' for the main program to use.
  10298.  
  10299.    If `thisopt' is not in the `options' string, then it is an invalid
  10300. option.  If `Opterr' is non-zero, `getopt' prints an error message on
  10301. the standard error that is similar to the message from the C version of
  10302. `getopt'.
  10303.  
  10304.    Since the option is invalid, it is necessary to skip it and move on
  10305. to the next option character.  If `_opti' is greater than or equal to
  10306. the length of the current command line argument, then it is necessary
  10307. to move on to the next one, so `Optind' is incremented and `_opti' is
  10308. reset to zero. Otherwise, `Optind' is left alone and `_opti' is merely
  10309. incremented.
  10310.  
  10311.    In any case, since the option was invalid, `getopt' returns `?'.
  10312. The main program can examine `Optopt' if it needs to know what the
  10313. invalid option letter actually was.
  10314.  
  10315.          if (substr(options, i + 1, 1) == ":") {
  10316.              # get option argument
  10317.              if (length(substr(argv[Optind], _opti + 1)) > 0)
  10318.                  Optarg = substr(argv[Optind], _opti + 1)
  10319.              else
  10320.                  Optarg = argv[++Optind]
  10321.              _opti = 0
  10322.          } else
  10323.              Optarg = ""
  10324.  
  10325.    If the option requires an argument, the option letter is followed by
  10326. a colon in the `options' string.  If there are remaining characters in
  10327. the current command line argument (`argv[Optind]'), then the rest of
  10328. that string is assigned to `Optarg'.  Otherwise, the next command line
  10329. argument is used (`-xFOO' vs. `-x FOO'). In either case, `_opti' is
  10330. reset to zero, since there are no more characters left to examine in
  10331. the current command line argument.
  10332.  
  10333.          if (_opti == 0 || _opti >= length(argv[Optind])) {
  10334.              Optind++
  10335.              _opti = 0
  10336.          } else
  10337.              _opti++
  10338.          return thisopt
  10339.      }
  10340.  
  10341.    Finally, if `_opti' is either zero or greater than the length of the
  10342. current command line argument, it means this element in `argv' is
  10343. through being processed, so `Optind' is incremented to point to the
  10344. next element in `argv'.  If neither condition is true, then only
  10345. `_opti' is incremented, so that the next option letter can be processed
  10346. on the next call to `getopt'.
  10347.  
  10348.      BEGIN {
  10349.          Opterr = 1    # default is to diagnose
  10350.          Optind = 1    # skip ARGV[0]
  10351.      
  10352.          # test program
  10353.          if (_getopt_test) {
  10354.              while ((_go_c = getopt(ARGC, ARGV, "ab:cd")) != -1)
  10355.                  printf("c = <%c>, optarg = <%s>\n",
  10356.                                             _go_c, Optarg)
  10357.              printf("non-option arguments:\n")
  10358.              for (; Optind < ARGC; Optind++)
  10359.                  printf("\tARGV[%d] = <%s>\n",
  10360.                                          Optind, ARGV[Optind])
  10361.          }
  10362.      }
  10363.  
  10364.    The `BEGIN' rule initializes both `Opterr' and `Optind' to one.
  10365. `Opterr' is set to one, since the default behavior is for `getopt' to
  10366. print a diagnostic message upon seeing an invalid option.  `Optind' is
  10367. set to one, since there's no reason to look at the program name, which
  10368. is in `ARGV[0]'.
  10369.  
  10370.    The rest of the `BEGIN' rule is a simple test program.  Here is the
  10371. result of two sample runs of the test program.
  10372.  
  10373.      $ awk -f getopt.awk -v _getopt_test=1 -- -a -cbARG bax -x
  10374.      -| c = <a>, optarg = <>
  10375.      -| c = <c>, optarg = <>
  10376.      -| c = <b>, optarg = <ARG>
  10377.      -| non-option arguments:
  10378.      -|         ARGV[3] = <bax>
  10379.      -|         ARGV[4] = <-x>
  10380.      
  10381.      $ awk -f getopt.awk -v _getopt_test=1 -- -a -x -- xyz abc
  10382.      -| c = <a>, optarg = <>
  10383.      error--> x -- invalid option
  10384.      -| c = <?>, optarg = <>
  10385.      -| non-option arguments:
  10386.      -|         ARGV[4] = <xyz>
  10387.      -|         ARGV[5] = <abc>
  10388.  
  10389.    The first `--' terminates the arguments to `awk', so that it does
  10390. not try to interpret the `-a' etc. as its own options.
  10391.  
  10392.    Several of the sample programs presented in *Note Practical `awk'
  10393. Programs: Sample Programs, use `getopt' to process their arguments.
  10394.  
  10395. 
  10396. File: gawk.info,  Node: Passwd Functions,  Next: Group Functions,  Prev: Getopt Function,  Up: Library Functions
  10397.  
  10398. Reading the User Database
  10399. =========================
  10400.  
  10401.    The `/dev/user' special file (*note Special File Names in `gawk':
  10402. Special Files.) provides access to the current user's real and
  10403. effective user and group id numbers, and if available, the user's
  10404. supplementary group set.  However, since these are numbers, they do not
  10405. provide very useful information to the average user.  There needs to be
  10406. some way to find the user information associated with the user and
  10407. group numbers.  This section presents a suite of functions for
  10408. retrieving information from the user database.  *Note Reading the Group
  10409. Database: Group Functions, for a similar suite that retrieves
  10410. information from the group database.
  10411.  
  10412.    The POSIX standard does not define the file where user information is
  10413. kept.  Instead, it provides the `<pwd.h>' header file and several C
  10414. language subroutines for obtaining user information.  The primary
  10415. function is `getpwent', for "get password entry." The "password" comes
  10416. from the original user database file, `/etc/passwd', which kept user
  10417. information, along with the encrypted passwords (hence the name).
  10418.  
  10419.    While an `awk' program could simply read `/etc/passwd' directly (the
  10420. format is well known), because of the way password files are handled on
  10421. networked systems, this file may not contain complete information about
  10422. the system's set of users.
  10423.  
  10424.    To be sure of being able to produce a readable, complete version of
  10425. the user database, it is necessary to write a small C program that
  10426. calls `getpwent'.  `getpwent' is defined to return a pointer to a
  10427. `struct passwd'.  Each time it is called, it returns the next entry in
  10428. the database.  When there are no more entries, it returns `NULL', the
  10429. null pointer.  When this happens, the C program should call `endpwent'
  10430. to close the database.  Here is `pwcat', a C program that "cats" the
  10431. password database.
  10432.  
  10433.      /*
  10434.       * pwcat.c
  10435.       *
  10436.       * Generate a printable version of the password database
  10437.       *
  10438.       * Arnold Robbins
  10439.       * arnold@gnu.ai.mit.edu
  10440.       * May 1993
  10441.       * Public Domain
  10442.       */
  10443.      
  10444.      #include <stdio.h>
  10445.      #include <pwd.h>
  10446.      
  10447.      int
  10448.      main(argc, argv)
  10449.      int argc;
  10450.      char **argv;
  10451.      {
  10452.          struct passwd *p;
  10453.      
  10454.          while ((p = getpwent()) != NULL)
  10455.              printf("%s:%s:%d:%d:%s:%s:%s\n",
  10456.                  p->pw_name, p->pw_passwd, p->pw_uid,
  10457.                  p->pw_gid, p->pw_gecos, p->pw_dir, p->pw_shell);
  10458.      
  10459.          endpwent();
  10460.          exit(0);
  10461.      }
  10462.  
  10463.    If you don't understand C, don't worry about it.  The output from
  10464. `pwcat' is the user database, in the traditional `/etc/passwd' format
  10465. of colon-separated fields.  The fields are:
  10466.  
  10467. Login name
  10468.      The user's login name.
  10469.  
  10470. Encrypted password
  10471.      The user's encrypted password.  This may not be available on some
  10472.      systems.
  10473.  
  10474. User-ID
  10475.      The user's numeric user-id number.
  10476.  
  10477. Group-ID
  10478.      The user's numeric group-id number.
  10479.  
  10480. Full name
  10481.      The user's full name, and perhaps other information associated
  10482.      with the user.
  10483.  
  10484. Home directory
  10485.      The user's login, or "home" directory (familiar to shell
  10486.      programmers as `$HOME').
  10487.  
  10488. Login shell
  10489.      The program that will be run when the user logs in.  This is
  10490.      usually a shell, such as Bash (the Gnu Bourne-Again shell).
  10491.  
  10492.    Here are a few lines representative of `pwcat''s output.
  10493.  
  10494.      $ pwcat
  10495.      -| root:3Ov02d5VaUPB6:0:1:Operator:/:/bin/sh
  10496.      -| nobody:*:65534:65534::/:
  10497.      -| daemon:*:1:1::/:
  10498.      -| sys:*:2:2::/:/bin/csh
  10499.      -| bin:*:3:3::/bin:
  10500.      -| arnold:xyzzy:2076:10:Arnold Robbins:/home/arnold:/bin/sh
  10501.      -| miriam:yxaay:112:10:Miriam Robbins:/home/miriam:/bin/sh
  10502.      ...
  10503.  
  10504.    With that introduction, here is a group of functions for getting user
  10505. information.  There are several functions here, corresponding to the C
  10506. functions of the same name.
  10507.  
  10508.      # passwd.awk --- access password file information
  10509.      # Arnold Robbins, arnold@gnu.ai.mit.edu, Public Domain
  10510.      # May 1993
  10511.      
  10512.      BEGIN {
  10513.          # tailor this to suit your system
  10514.          _pw_awklib = "/usr/local/libexec/awk/"
  10515.      }
  10516.      
  10517.      function _pw_init(    oldfs, oldrs, olddol0, pwcat)
  10518.      {
  10519.          if (_pw_inited)
  10520.              return
  10521.          oldfs = FS
  10522.          oldrs = RS
  10523.          olddol0 = $0
  10524.          FS = ":"
  10525.          RS = "\n"
  10526.          pwcat = _pw_awklib "pwcat"
  10527.          while ((pwcat | getline) > 0) {
  10528.              _pw_byname[$1] = $0
  10529.              _pw_byuid[$3] = $0
  10530.              _pw_bycount[++_pw_total] = $0
  10531.          }
  10532.          close(pwcat)
  10533.          _pw_count = 0
  10534.          _pw_inited = 1
  10535.          FS = oldfs
  10536.          RS = oldrs
  10537.          $0 = olddol0
  10538.      }
  10539.  
  10540.    The `BEGIN' rule sets a private variable to the directory where
  10541. `pwcat' is stored.  Since it is used to help out an `awk' library
  10542. routine, we have chosen to put it in `/usr/local/libexec/awk'.  You
  10543. might want it to be in a different directory on your system.
  10544.  
  10545.    The function `_pw_init' keeps three copies of the user information
  10546. in three associative arrays.  The arrays are indexed by user name
  10547. (`_pw_byname'), by user-id number (`_pw_byuid'), and by order of
  10548. occurrence (`_pw_bycount').
  10549.  
  10550.    The variable `_pw_inited' is used for efficiency; `_pw_init' only
  10551. needs to be called once.
  10552.  
  10553.    Since this function uses `getline' to read information from `pwcat',
  10554. it first saves the values of `FS', `RS', and `$0'.  Doing so is
  10555. necessary, since these functions could be called from anywhere within a
  10556. user's program, and the user may have his or her own values for `FS'
  10557. and `RS'.
  10558.  
  10559.    The main part of the function uses a loop to read database lines,
  10560. split the line into fields, and then store the line into each array as
  10561. necessary.  When the loop is done, `_pw_init' cleans up by closing the
  10562. pipeline, setting `_pw_inited' to one, and restoring `FS', `RS', and
  10563. `$0'.  The use of `_pw_count' will be explained below.
  10564.  
  10565.      function getpwnam(name)
  10566.      {
  10567.          _pw_init()
  10568.          if (name in _pw_byname)
  10569.              return _pw_byname[name]
  10570.          return ""
  10571.      }
  10572.  
  10573.    The `getpwnam' function takes a user name as a string argument. If
  10574. that user is in the database, it returns the appropriate line.
  10575. Otherwise it returns the null string.
  10576.  
  10577.      function getpwuid(uid)
  10578.      {
  10579.          _pw_init()
  10580.          if (uid in _pw_byuid)
  10581.              return _pw_byuid[uid]
  10582.          return ""
  10583.      }
  10584.  
  10585.    Similarly, the `getpwuid' function takes a user-id number argument.
  10586. If that user number is in the database, it returns the appropriate
  10587. line. Otherwise it returns the null string.
  10588.  
  10589.      function getpwent()
  10590.      {
  10591.          _pw_init()
  10592.          if (_pw_count < _pw_total)
  10593.              return _pw_bycount[++_pw_count]
  10594.          return ""
  10595.      }
  10596.  
  10597.    The `getpwent' function simply steps through the database, one entry
  10598. at a time.  It uses `_pw_count' to track its current position in the
  10599. `_pw_bycount' array.
  10600.  
  10601.      function endpwent()
  10602.      {
  10603.          _pw_count = 0
  10604.      }
  10605.  
  10606.    The `endpwent' function resets `_pw_count' to zero, so that
  10607. subsequent calls to `getpwent' will start over again.
  10608.  
  10609.    A conscious design decision in this suite is that each subroutine
  10610. calls `_pw_init' to initialize the database arrays.  The overhead of
  10611. running a separate process to generate the user database, and the I/O
  10612. to scan it, will only be incurred if the user's main program actually
  10613. calls one of these functions.  If this library file is loaded along
  10614. with a user's program, but none of the routines are ever called, then
  10615. there is no extra run-time overhead.  (The alternative would be to move
  10616. the body of `_pw_init' into a `BEGIN' rule, which would always run
  10617. `pwcat'.  This simplifies the code but runs an extra process that may
  10618. never be needed.)
  10619.  
  10620.    In turn, calling `_pw_init' is not too expensive, since the
  10621. `_pw_inited' variable keeps the program from reading the data more than
  10622. once.  If you are worried about squeezing every last cycle out of your
  10623. `awk' program, the check of `_pw_inited' could be moved out of
  10624. `_pw_init' and duplicated in all the other functions.  In practice,
  10625. this is not necessary, since most `awk' programs are I/O bound, and it
  10626. would clutter up the code.
  10627.  
  10628.    The `id' program in *Note Printing Out User Information: Id Program,
  10629. uses these functions.
  10630.  
  10631. 
  10632. File: gawk.info,  Node: Group Functions,  Next: Library Names,  Prev: Passwd Functions,  Up: Library Functions
  10633.  
  10634. Reading the Group Database
  10635. ==========================
  10636.  
  10637.    Much of the discussion presented in *Note Reading the User Database:
  10638. Passwd Functions, applies to the group database as well.  Although
  10639. there has traditionally been a well known file, `/etc/group', in a well
  10640. known format, the POSIX standard only provides a set of C library
  10641. routines (`<grp.h>' and `getgrent') for accessing the information.
  10642. Even though this file may exist, it likely does not have complete
  10643. information.  Therefore, as with the user database, it is necessary to
  10644. have a small C program that generates the group database as its output.
  10645.  
  10646.    Here is `grcat', a C program that "cats" the group database.
  10647.  
  10648.      /*
  10649.       * grcat.c
  10650.       *
  10651.       * Generate a printable version of the group database
  10652.       *
  10653.       * Arnold Robbins, arnold@gnu.ai.mit.edu
  10654.       * May 1993
  10655.       * Public Domain
  10656.       */
  10657.      
  10658.      #include <stdio.h>
  10659.      #include <grp.h>
  10660.      
  10661.      int
  10662.      main(argc, argv)
  10663.      int argc;
  10664.      char **argv;
  10665.      {
  10666.          struct group *g;
  10667.          int i;
  10668.      
  10669.          while ((g = getgrent()) != NULL) {
  10670.              printf("%s:%s:%d:", g->gr_name, g->gr_passwd,
  10671.                                                  g->gr_gid);
  10672.              for (i = 0; g->gr_mem[i] != NULL; i++) {
  10673.                  printf("%s", g->gr_mem[i]);
  10674.                  if (g->gr_mem[i+1] != NULL)
  10675.                      putchar(',');
  10676.              }
  10677.              putchar('\n');
  10678.          }
  10679.          endgrent();
  10680.          exit(0);
  10681.      }
  10682.  
  10683.    Each line in the group database represent one group.  The fields are
  10684. separated with colons, and represent the following information.
  10685.  
  10686. Group Name
  10687.      The name of the group.
  10688.  
  10689. Group Password
  10690.      The encrypted group password. In practice, this field is never
  10691.      used. It is usually empty, or set to `*'.
  10692.  
  10693. Group ID Number
  10694.      The numeric group-id number. This number should be unique within
  10695.      the file.
  10696.  
  10697. Group Member List
  10698.      A comma-separated list of user names.  These users are members of
  10699.      the group.  Most Unix systems allow users to be members of several
  10700.      groups simultaneously.  If your system does, then reading
  10701.      `/dev/user' will return those group-id numbers in `$5' through
  10702.      `$NF'.  (Note that `/dev/user' is a `gawk' extension; *note
  10703.      Special File Names in `gawk': Special Files..)
  10704.  
  10705.    Here is what running `grcat' might produce:
  10706.  
  10707.      $ grcat
  10708.      -| wheel:*:0:arnold
  10709.      -| nogroup:*:65534:
  10710.      -| daemon:*:1:
  10711.      -| kmem:*:2:
  10712.      -| staff:*:10:arnold,miriam,andy
  10713.      -| other:*:20:
  10714.      ...
  10715.  
  10716.    Here are the functions for obtaining information from the group
  10717. database.  There are several, modeled after the C library functions of
  10718. the same names.
  10719.  
  10720.      # group.awk --- functions for dealing with the group file
  10721.      # Arnold Robbins, arnold@gnu.ai.mit.edu, Public Domain
  10722.      # May 1993
  10723.      
  10724.      BEGIN    \
  10725.      {
  10726.          # Change to suit your system
  10727.          _gr_awklib = "/usr/local/libexec/awk/"
  10728.      }
  10729.      
  10730.      function _gr_init(    oldfs, oldrs, olddol0, grcat, n, a, i)
  10731.      {
  10732.          if (_gr_inited)
  10733.              return
  10734.      
  10735.          oldfs = FS
  10736.          oldrs = RS
  10737.          olddol0 = $0
  10738.          FS = ":"
  10739.          RS = "\n"
  10740.      
  10741.          grcat = _gr_awklib "grcat"
  10742.          while ((grcat | getline) > 0) {
  10743.              if ($1 in _gr_byname)
  10744.                  _gr_byname[$1] = _gr_byname[$1] "," $4
  10745.              else
  10746.                  _gr_byname[$1] = $0
  10747.              if ($3 in _gr_bygid)
  10748.                  _gr_bygid[$3] = _gr_bygid[$3] "," $4
  10749.              else
  10750.                  _gr_bygid[$3] = $0
  10751.      
  10752.              n = split($4, a, "[ \t]*,[ \t]*")
  10753.              for (i = 1; i <= n; i++)
  10754.                  if (a[i] in _gr_groupsbyuser)
  10755.                      _gr_groupsbyuser[a[i]] = \
  10756.                          _gr_groupsbyuser[a[i]] " " $1
  10757.                  else
  10758.                      _gr_groupsbyuser[a[i]] = $1
  10759.      
  10760.              _gr_bycount[++_gr_count] = $0
  10761.          }
  10762.          close(grcat)
  10763.          _gr_count = 0
  10764.          _gr_inited++
  10765.          FS = oldfs
  10766.          RS = oldrs
  10767.          $0 = olddol0
  10768.      }
  10769.  
  10770.    The `BEGIN' rule sets a private variable to the directory where
  10771. `grcat' is stored.  Since it is used to help out an `awk' library
  10772. routine, we have chosen to put it in `/usr/local/libexec/awk'.  You
  10773. might want it to be in a different directory on your system.
  10774.  
  10775.    These routines follow the same general outline as the user database
  10776. routines (*note Reading the User Database: Passwd Functions.).  The
  10777. `_gr_inited' variable is used to ensure that the database is scanned no
  10778. more than once.  The `_gr_init' function first saves `FS', `RS', and
  10779. `$0', and then sets `FS' and `RS' to the correct values for scanning
  10780. the group information.
  10781.  
  10782.    The group information is stored is several associative arrays.  The
  10783. arrays are indexed by group name (`_gr_byname'), by group-id number
  10784. (`_gr_bygid'), and by position in the database (`_gr_bycount').  There
  10785. is an additional array indexed by user name (`_gr_groupsbyuser'), that
  10786. is a space separated list of groups that each user belongs to.
  10787.  
  10788.    Unlike the user database, it is possible to have multiple records in
  10789. the database for the same group.  This is common when a group has a
  10790. large number of members.  Such a pair of entries might look like:
  10791.  
  10792.      tvpeople:*:101:johny,jay,arsenio
  10793.      tvpeople:*:101:david,conan,tom,joan
  10794.  
  10795.    For this reason, `_gr_init' looks to see if a group name or group-id
  10796. number has already been seen.  If it has, then the user names are
  10797. simply concatenated onto the previous list of users.  (There is
  10798. actually a subtle problem with the code presented above.  Suppose that
  10799. the first time there were no names. This code adds the names with a
  10800. leading comma. It also doesn't check that there is a `$4'.)
  10801.  
  10802.    Finally, `_gr_init' closes the pipeline to `grcat', restores `FS',
  10803. `RS', and `$0', initializes `_gr_count' to zero (it is used later), and
  10804. makes `_gr_inited' non-zero.
  10805.  
  10806.      function getgrnam(group)
  10807.      {
  10808.          _gr_init()
  10809.          if (group in _gr_byname)
  10810.              return _gr_byname[group]
  10811.          return ""
  10812.      }
  10813.  
  10814.    The `getgrnam' function takes a group name as its argument, and if
  10815. that group exists, it is returned. Otherwise, `getgrnam' returns the
  10816. null string.
  10817.  
  10818.      function getgrgid(gid)
  10819.      {
  10820.          _gr_init()
  10821.          if (gid in _gr_bygid)
  10822.              return _gr_bygid[gid]
  10823.          return ""
  10824.      }
  10825.  
  10826.    The `getgrgid' function is similar, it takes a numeric group-id, and
  10827. looks up the information associated with that group-id.
  10828.  
  10829.      function getgruser(user)
  10830.      {
  10831.          _gr_init()
  10832.          if (user in _gr_groupsbyuser)
  10833.              return _gr_groupsbyuser[user]
  10834.          return ""
  10835.      }
  10836.  
  10837.    The `getgruser' function does not have a C counterpart. It takes a
  10838. user name, and returns the list of groups that have the user as a
  10839. member.
  10840.  
  10841.      function getgrent()
  10842.      {
  10843.          _gr_init()
  10844.          if (++gr_count in _gr_bycount)
  10845.              return _gr_bycount[_gr_count]
  10846.          return ""
  10847.      }
  10848.  
  10849.    The `getgrent' function steps through the database one entry at a
  10850. time.  It uses `_gr_count' to track its position in the list.
  10851.  
  10852.      function endgrent()
  10853.      {
  10854.          _gr_count = 0
  10855.      }
  10856.  
  10857.    `endgrent' resets `_gr_count' to zero so that `getgrent' can start
  10858. over again.
  10859.  
  10860.    As with the user database routines, each function calls `_gr_init' to
  10861. initialize the arrays.  Doing so only incurs the extra overhead of
  10862. running `grcat' if these functions are used (as opposed to moving the
  10863. body of `_gr_init' into a `BEGIN' rule).
  10864.  
  10865.    Most of the work is in scanning the database and building the various
  10866. associative arrays.  The functions that the user calls are themselves
  10867. very simple, relying on `awk''s associative arrays to do work.
  10868.  
  10869.    The `id' program in *Note Printing Out User Information: Id Program,
  10870. uses these functions.
  10871.  
  10872. 
  10873. File: gawk.info,  Node: Library Names,  Prev: Group Functions,  Up: Library Functions
  10874.  
  10875. Naming Library Function Global Variables
  10876. ========================================
  10877.  
  10878.    Due to the way the `awk' language evolved, variables are either
  10879. "global" (usable by the entire program), or "local" (usable just by a
  10880. specific function).  There is no intermediate state analogous to
  10881. `static' variables in C.
  10882.  
  10883.    Library functions often need to have global variables that they can
  10884. use to preserve state information between calls to the function. For
  10885. example, `getopt''s variable `_opti' (*note Processing Command Line
  10886. Options: Getopt Function.), and the `_tm_months' array used by `mktime'
  10887. (*note Turning Dates Into Timestamps: Mktime Function.).  Such
  10888. variables are called "private", since the only functions that need to
  10889. use them are the ones in the library.
  10890.  
  10891.    When writing a library function, you should try to choose names for
  10892. your private variables so that they will not conflict with any
  10893. variables used by either another library function or a user's main
  10894. program.  For example, a name like `i' or `j' is not a good choice,
  10895. since user programs often use variable names like these for their own
  10896. purposes.
  10897.  
  10898.    The example programs shown in this chapter all start the names of
  10899. their private variables with an underscore (`_').  Users generally
  10900. don't use leading underscores in their variable names, so this
  10901. convention immediately decreases the chances that the variable name
  10902. will be accidentally shared with the user's program.
  10903.  
  10904.    In addition, several of the library functions use a prefix that helps
  10905. indicate what function or set of functions uses the variables. For
  10906. example, `_tm_months' in `mktime' (*note Turning Dates Into Timestamps:
  10907. Mktime Function.), and `_pw_byname' in the user data base routines
  10908. (*note Reading the User Database: Passwd Functions.).  This convention
  10909. is recommended, since it even further decreases the chance of
  10910. inadvertent conflict among variable names.  Note that this convention
  10911. can be used equally well both for variable names and for private
  10912. function names too.
  10913.  
  10914.    While I could have re-written all the library routines to use this
  10915. convention, I did not do so, in order to show how my own `awk'
  10916. programming style has evolved, and to provide some basis for this
  10917. discussion.
  10918.  
  10919.    As a final note on variable naming, if a function makes global
  10920. variables available for use by a main program, it is a good convention
  10921. to start that variable's name with a capital letter.  For example,
  10922. `getopt''s `Opterr' and `Optind' variables (*note Processing Command
  10923. Line Options: Getopt Function.).  The leading capital letter indicates
  10924. that it is global, while the fact that the variable name is not all
  10925. capital letters indicates that the variable is not one of `awk''s
  10926. built-in variables, like `FS'.
  10927.  
  10928.    It is also important that *all* variables in library functions that
  10929. do not need to save state are in fact declared local.  If this is not
  10930. done, the variable could accidentally be used in the user's program,
  10931. leading to bugs that are very difficult to track down.
  10932.  
  10933.      function lib_func(x, y,    l1, l2)
  10934.      {
  10935.          ...
  10936.          USE VARIABLE some_var  # some_var could be local
  10937.          ...                   # but is not by oversight
  10938.      }
  10939.  
  10940.    A different convention, common in the Tcl community, is to use a
  10941. single associative array to hold the values needed by the library
  10942. function(s), or "package."  This significantly decreases the number of
  10943. actual global names in use.  For example, the functions described in
  10944. *Note Reading the User Database: Passwd Functions, might have used
  10945. `PW_data["inited"]', `PW_data["total"]', `PW_data["count"]' and
  10946. `PW_data["awklib"]', instead of `_pw_inited', `_pw_awklib', `_pw_total',
  10947. and `_pw_count'.
  10948.  
  10949.    The conventions presented in this section are exactly that,
  10950. conventions. You are not required to write your programs this way, we
  10951. merely recommend that you do so.
  10952.  
  10953. 
  10954. File: gawk.info,  Node: Sample Programs,  Next: Language History,  Prev: Library Functions,  Up: Top
  10955.  
  10956. Practical `awk' Programs
  10957. ************************
  10958.  
  10959.    This chapter presents a potpourri of `awk' programs for your reading
  10960. enjoyment.
  10961.  
  10962.    Many of these programs use the library functions presented in *Note
  10963. A Library of `awk' Functions: Library Functions.
  10964.  
  10965. * Menu:
  10966.  
  10967. * Clones::                    Clones of common utilities.
  10968. * Miscellaneous Programs::    Some interesting `awk' programs.
  10969.  
  10970. 
  10971. File: gawk.info,  Node: Clones,  Next: Miscellaneous Programs,  Prev: Sample Programs,  Up: Sample Programs
  10972.  
  10973. Re-inventing Wheels for Fun and Profit
  10974. ======================================
  10975.  
  10976.    This section presents a number of POSIX utilities that are
  10977. implemented in `awk'.  Re-inventing these programs in `awk' is often
  10978. enjoyable, since the algorithms can be very clearly expressed, and
  10979. usually the code is very concise and simple.  This is true because
  10980. `awk' does so much for you.
  10981.  
  10982.    It should be noted that these programs are not necessarily intended
  10983. to replace the installed versions on your system.  Instead, their
  10984. purpose is to illustrate `awk' language programming for "real world"
  10985. tasks.
  10986.  
  10987.    The programs are presented in alphabetical order.
  10988.  
  10989. * Menu:
  10990.  
  10991. * Cut Program::             The `cut' utility.
  10992. * Egrep Program::           The `egrep' utility.
  10993. * Id Program::              The `id' utility.
  10994. * Split Program::           The `split' utility.
  10995. * Tee Program::             The `tee' utility.
  10996. * Uniq Program::            The `uniq' utility.
  10997. * Wc Program::              The `wc' utility.
  10998.  
  10999. 
  11000. File: gawk.info,  Node: Cut Program,  Next: Egrep Program,  Prev: Clones,  Up: Clones
  11001.  
  11002. Cutting Out Fields and Columns
  11003. ------------------------------
  11004.  
  11005.    The `cut' utility selects, or "cuts," either characters or fields
  11006. from its standard input and sends them to its standard output.  `cut'
  11007. can cut out either a list of characters, or a list of fields.  By
  11008. default, fields are separated by tabs, but you may supply a command
  11009. line option to change the field "delimiter", i.e. the field separator
  11010. character. `cut''s definition of fields is less general than `awk''s.
  11011.  
  11012.    A common use of `cut' might be to pull out just the login name of
  11013. logged-on users from the output of `who'.  For example, the following
  11014. pipeline generates a sorted, unique list of the logged on users:
  11015.  
  11016.      who | cut -c1-8 | sort | uniq
  11017.  
  11018.    The options for `cut' are:
  11019.  
  11020. `-c LIST'
  11021.      Use LIST as the list of characters to cut out.  Items within the
  11022.      list may be separated by commas, and ranges of characters can be
  11023.      separated with dashes.  The list `1-8,15,22-35' specifies
  11024.      characters one through eight, 15, and 22 through 35.
  11025.  
  11026. `-f LIST'
  11027.      Use LIST as the list of fields to cut out.
  11028.  
  11029. `-d DELIM'
  11030.      Use DELIM as the field separator character instead of the tab
  11031.      character.
  11032.  
  11033. `-s'
  11034.      Suppress printing of lines that do not contain the field delimiter.
  11035.  
  11036.    The `awk' implementation of `cut' uses the `getopt' library function
  11037. (*note Processing Command Line Options: Getopt Function.), and the
  11038. `join' library function (*note Merging an Array Into a String: Join
  11039. Function.).
  11040.  
  11041.    The program begins with a comment describing the options and a
  11042. `usage' function which prints out a usage message and exits.  `usage'
  11043. is called if invalid arguments are supplied.
  11044.  
  11045.      # cut.awk --- implement cut in awk
  11046.      # Arnold Robbins, arnold@gnu.ai.mit.edu, Public Domain
  11047.      # May 1993
  11048.      
  11049.      # Options:
  11050.      #    -f list        Cut fields
  11051.      #    -d c           Field delimiter character
  11052.      #    -c list        Cut characters
  11053.      #
  11054.      #    -s        Suppress lines without the delimiter character
  11055.      
  11056.      function usage(    e1, e2)
  11057.      {
  11058.          e1 = "usage: cut [-f list] [-d c] [-s] [files...]"
  11059.          e2 = "usage: cut [-c list] [files...]"
  11060.          print e1 > "/dev/stderr"
  11061.          print e2 > "/dev/stderr"
  11062.          exit 1
  11063.      }
  11064.  
  11065. The variables `e1' and `e2' are used so that the function fits nicely
  11066. on the screen.
  11067.  
  11068.    Next comes a `BEGIN' rule that parses the command line options.  It
  11069. sets `FS' to a single tab character, since that is `cut''s default
  11070. field separator.  The output field separator is also set to be the same
  11071. as the input field separator.  Then `getopt' is used to step through
  11072. the command line options.  One or the other of the variables
  11073. `by_fields' or `by_chars' is set to true, to indicate that processing
  11074. should be done by fields or by characters respectively.  When cutting
  11075. by characters, the output field separator is set to the null string.
  11076.  
  11077.      BEGIN    \
  11078.      {
  11079.          FS = "\t"    # default
  11080.          OFS = FS
  11081.          while ((c = getopt(ARGC, ARGV, "sf:c:d:")) != -1) {
  11082.              if (c == "f") {
  11083.                  by_fields = 1
  11084.                  fieldlist = Optarg
  11085.              } else if (c == "c") {
  11086.                  by_chars = 1
  11087.                  fieldlist = Optarg
  11088.                  OFS = ""
  11089.              } else if (c == "d") {
  11090.                  if (length(Optarg) > 1) {
  11091.                      printf("Using first character of %s" \
  11092.                      " for delimiter\n", Optarg) > "/dev/stderr"
  11093.                      Optarg = substr(Optarg, 1, 1)
  11094.                  }
  11095.                  FS = Optarg
  11096.                  OFS = FS
  11097.                  if (FS == " ")    # defeat awk semantics
  11098.                      FS = "[ ]"
  11099.              } else if (c == "s")
  11100.                  suppress++
  11101.              else
  11102.                  usage()
  11103.          }
  11104.      
  11105.          for (i = 1; i < Optind; i++)
  11106.              ARGV[i] = ""
  11107.  
  11108.    Special care is taken when the field delimiter is a space. Using
  11109. `" "' (a single space) for the value of `FS' is incorrect--`awk' would
  11110. separate fields with runs of spaces and/or tabs, and we want them to be
  11111. separated with individual spaces.  Also, note that after `getopt' is
  11112. through, we have to clear out all the elements of `ARGV' from one to
  11113. `Optind', so that `awk' will not try to process the command line
  11114. options as file names.
  11115.  
  11116.    After dealing with the command line options, the program verifies
  11117. that the options make sense.  Only one or the other of `-c' and `-f'
  11118. should be used, and both require a field list.  Then either
  11119. `set_fieldlist' or `set_charlist' is called to pull apart the list of
  11120. fields or characters.
  11121.  
  11122.          if (by_fields && by_chars)
  11123.              usage()
  11124.      
  11125.          if (by_fields == 0 && by_chars == 0)
  11126.              by_fields = 1    # default
  11127.      
  11128.          if (fieldlist == "") {
  11129.              print "cut: needs list for -c or -f" > "/dev/stderr"
  11130.              exit 1
  11131.          }
  11132.      
  11133.          if (by_fields)
  11134.              set_fieldlist()
  11135.          else
  11136.              set_charlist()
  11137.      }
  11138.  
  11139.    Here is `set_fieldlist'.  It first splits the field list apart at
  11140. the commas, into an array.  Then, for each element of the array, it
  11141. looks to see if it is actually a range, and if so splits it apart. The
  11142. range is verified to make sure the first number is smaller than the
  11143. second.  Each number in the list is added to the `flist' array, which
  11144. simply lists the fields that will be printed.  Normal field splitting
  11145. is used.  The program lets `awk' handle the job of doing the field
  11146. splitting.
  11147.  
  11148.      function set_fieldlist(        n, m, i, j, k, f, g)
  11149.      {
  11150.          n = split(fieldlist, f, ",")
  11151.          j = 1    # index in flist
  11152.          for (i = 1; i <= n; i++) {
  11153.              if (index(f[i], "-") != 0) { # a range
  11154.                  m = split(f[i], g, "-")
  11155.                  if (m != 2 || g[1] >= g[2]) {
  11156.                      printf("bad field list: %s\n",
  11157.                                        f[i]) > "/dev/stderr"
  11158.                      exit 1
  11159.                  }
  11160.                  for (k = g[1]; k <= g[2]; k++)
  11161.                      flist[j++] = k
  11162.              } else
  11163.                  flist[j++] = f[i]
  11164.          }
  11165.          nfields = j - 1
  11166.      }
  11167.  
  11168.    The `set_charlist' function is more complicated than `set_fieldlist'.
  11169. The idea here is to use `gawk''s `FIELDWIDTHS' variable (*note Reading
  11170. Fixed-width Data: Constant Size.), which describes constant width
  11171. input.  When using a character list, that is exactly what we have.
  11172.  
  11173.    Setting up `FIELDWIDTHS' is more complicated than simply listing the
  11174. fields that need to be printed.  We have to keep track of the fields to
  11175. be printed, and also the intervening characters that have to be skipped.
  11176. For example, suppose you wanted characters one through eight, 15, and
  11177. 22 through 35.  You would use `-c 1-8,15,22-35'.  The necessary value
  11178. for `FIELDWIDTHS' would be `"8 6 1 6 14"'.  This gives us five fields,
  11179. and what should be printed are `$1', `$3', and `$5'.  The intermediate
  11180. fields are "filler," stuff in between the desired data.
  11181.  
  11182.    `flist' lists the fields to be printed, and `t' tracks the complete
  11183. field list, including filler fields.
  11184.  
  11185.      function set_charlist(    field, i, j, f, g, t,
  11186.                                filler, last, len)
  11187.      {
  11188.          field = 1   # count total fields
  11189.          n = split(fieldlist, f, ",")
  11190.          j = 1       # index in flist
  11191.          for (i = 1; i <= n; i++) {
  11192.              if (index(f[i], "-") != 0) { # range
  11193.                  m = split(f[i], g, "-")
  11194.                  if (m != 2 || g[1] >= g[2]) {
  11195.                      printf(bad character list: %s\n",
  11196.                                     f[i]) > "/dev/stderr"
  11197.                      exit 1
  11198.                  }
  11199.                  len = g[2] - g[1] + 1
  11200.                  if (g[1] > 1)  # compute length of filler
  11201.                      filler = g[1] - last - 1
  11202.                  else
  11203.                      filler = 0
  11204.                  if (filler)
  11205.                      t[field++] = filler
  11206.                  t[field++] = len  # length of field
  11207.                  last = g[2]
  11208.                  flist[j++] = field - 1
  11209.              } else {
  11210.                  if (f[i] > 1)
  11211.                      filler = f[i] - last - 1
  11212.                  else
  11213.                      filler = 0
  11214.                  if (filler)
  11215.                      t[field++] = filler
  11216.                  t[field++] = 1
  11217.                  last = f[i]
  11218.                  flist[j++] = field - 1
  11219.              }
  11220.          }
  11221.          FIELDWIDTHS = join(t, 1, field - 1)
  11222.          nfields = j - 1
  11223.      }
  11224.  
  11225.    Here is the rule that actually processes the data.  If the `-s'
  11226. option was given, then `suppress' will be true.  The first `if'
  11227. statement makes sure that the input record does have the field
  11228. separator.  If `cut' is processing fields, `suppress' is true, and the
  11229. field separator character is not in the record, then the record is
  11230. skipped.
  11231.  
  11232.    If the record is valid, then at this point, `gawk' has split the data
  11233. into fields, either using the character in `FS' or using fixed-length
  11234. fields and `FIELDWIDTHS'.  The loop goes through the list of fields
  11235. that should be printed.  If the corresponding field has data in it, it
  11236. is printed.  If the next field also has data, then the separator
  11237. character is written out in between the fields.
  11238.  
  11239.      {
  11240.          if (by_fields && suppress && $0 !~ FS)
  11241.              next
  11242.      
  11243.          for (i = 1; i <= nfields; i++) {
  11244.              if ($flist[i] != "") {
  11245.                  printf "%s", $flist[i]
  11246.                  if (i < nfields && $flist[i+1] != "")
  11247.                      printf "%s", OFS
  11248.              }
  11249.          }
  11250.          print ""
  11251.      }
  11252.  
  11253.    This version of `cut' relies on `gawk''s `FIELDWIDTHS' variable to
  11254. do the character-based cutting.  While it would be possible in other
  11255. `awk' implementations to use `substr' (*note Built-in Functions for
  11256. String Manipulation: String Functions.), it would also be extremely
  11257. painful to do so.  The `FIELDWIDTHS' variable supplies an elegant
  11258. solution to the problem of picking the input line apart by characters.
  11259.  
  11260. 
  11261. File: gawk.info,  Node: Egrep Program,  Next: Id Program,  Prev: Cut Program,  Up: Clones
  11262.  
  11263. Searching for Regular Expressions in Files
  11264. ------------------------------------------
  11265.  
  11266.    The `egrep' utility searches files for patterns.  It uses regular
  11267. expressions that are almost identical to those available in `awk'
  11268. (*note Regular Expression Constants: Regexp Constants.).  It is used
  11269. this way:
  11270.  
  11271.      egrep [ OPTIONS ] 'PATTERN' FILES ...
  11272.  
  11273.    The PATTERN is a regexp.  In typical usage, the regexp is quoted to
  11274. prevent the shell from expanding any of the special characters as file
  11275. name wildcards.  Normally, `egrep' prints the lines that matched.  If
  11276. multiple file names are provided on the command line, each output line
  11277. is preceded by the name of the file and a colon.
  11278.  
  11279.    The options are:
  11280.  
  11281. `-c'
  11282.      Print out a count of the lines that matched the pattern, instead
  11283.      of the lines themselves.
  11284.  
  11285. `-s'
  11286.      Be silent.  No output is produced, and the exit value indicates
  11287.      whether or not the pattern was matched.
  11288.  
  11289. `-v'
  11290.      Invert the sense of the test. `egrep' prints the lines that do
  11291.      *not* match the pattern, and exits successfully if the pattern was
  11292.      not matched.
  11293.  
  11294. `-i'
  11295.      Ignore case distinctions in both the pattern and the input data.
  11296.  
  11297. `-l'
  11298.      Only print the names of the files that matched, not the lines that
  11299.      matched.
  11300.  
  11301. `-e PATTERN'
  11302.      Use PATTERN as the regexp to match.  The purpose of the `-e'
  11303.      option is to allow patterns that start with a `-'.
  11304.  
  11305.    This version uses the `getopt' library function (*note Processing
  11306. Command Line Options: Getopt Function.), and the file transition
  11307. library program (*note Noting Data File Boundaries: Filetrans
  11308. Function.).
  11309.  
  11310.    The program begins with a descriptive comment, and then a `BEGIN'
  11311. rule that processes the command line arguments with `getopt'.  The `-i'
  11312. (ignore case) option is particularly easy with `gawk'; we just use the
  11313. `IGNORECASE' built in variable (*note Built-in Variables::.).
  11314.  
  11315.      # egrep.awk --- simulate egrep in awk
  11316.      # Arnold Robbins, arnold@gnu.ai.mit.edu, Public Domain
  11317.      # May 1993
  11318.      
  11319.      # Options:
  11320.      #    -c    count of lines
  11321.      #    -s    silent - use exit value
  11322.      #    -v    invert test, success if no match
  11323.      #    -i    ignore case
  11324.      #    -l    print filenames only
  11325.      #    -e    argument is pattern
  11326.      
  11327.      BEGIN {
  11328.          while ((c = getopt(ARGC, ARGV, "ce:svil")) != -1) {
  11329.              if (c == "c")
  11330.                  count_only++
  11331.              else if (c == "s")
  11332.                  no_print++
  11333.              else if (c == "v")
  11334.                  invert++
  11335.              else if (c == "i")
  11336.                  IGNORECASE = 1
  11337.              else if (c == "l")
  11338.                  filenames_only++
  11339.              else if (c == "e")
  11340.                  pattern = Optarg
  11341.              else
  11342.                  usage()
  11343.          }
  11344.  
  11345.    Next comes the code that handles the `egrep' specific behavior. If no
  11346. pattern was supplied with `-e', the first non-option on the command
  11347. line is used.  The `awk' command line arguments up to `ARGV[Optind]'
  11348. are cleared, so that `awk' won't try to process them as files.  If no
  11349. files were specified, the standard input is used, and if multiple files
  11350. were specified, we make sure to note this so that the file names can
  11351. precede the matched lines in the output.
  11352.  
  11353.    The last two lines are commented out, since they are not needed in
  11354. `gawk'.  They should be uncommented if you have to use another version
  11355. of `awk'.
  11356.  
  11357.          if (pattern == "")
  11358.              pattern = ARGV[Optind++]
  11359.      
  11360.          for (i = 1; i < Optind; i++)
  11361.              ARGV[i] = ""
  11362.          if (Optind >= ARGC) {
  11363.              ARGV[1] = "-"
  11364.              ARGC = 2
  11365.          } else if (ARGC - Optind > 1)
  11366.              do_filenames++
  11367.      
  11368.      #    if (IGNORECASE)
  11369.      #        pattern = tolower(pattern)
  11370.      }
  11371.  
  11372.    The next set of lines should be uncommented if you are not using
  11373. `gawk'.  This rule translates all the characters in the input line into
  11374. lower-case if the `-i' option was specified.  The rule is commented out
  11375. since it is not necessary with `gawk'.
  11376.  
  11377.      #{
  11378.      #    if (IGNORECASE)
  11379.      #        $0 = tolower($0)
  11380.      #}
  11381.  
  11382.    The `beginfile' function is called by the rule in `ftrans.awk' when
  11383. each new file is processed.  In this case, it is very simple; all it
  11384. does is initialize a variable `fcount' to zero. `fcount' tracks how
  11385. many lines in the current file matched the pattern.
  11386.  
  11387.      function beginfile(junk)
  11388.      {
  11389.          fcount = 0
  11390.      }
  11391.  
  11392.    The `endfile' function is called after each file has been processed.
  11393. It is used only when the user wants a count of the number of lines that
  11394. matched.  `no_print' will be true only if the exit status is desired.
  11395. `count_only' will be true if line counts are desired.  `egrep' will
  11396. therefore only print line counts if printing and counting are enabled.
  11397. The output format must be adjusted depending upon the number of files
  11398. to be processed.  Finally, `fcount' is added to `total', so that we
  11399. know how many lines altogether matched the pattern.
  11400.  
  11401.      function endfile(file)
  11402.      {
  11403.          if (! no_print && count_only)
  11404.              if (do_filenames)
  11405.                  print file ":" fcount
  11406.              else
  11407.                  print fcount
  11408.      
  11409.          total += fcount
  11410.      }
  11411.  
  11412.    This rule does most of the work of matching lines. The variable
  11413. `matches' will be true if the line matched the pattern. If the user
  11414. wants lines that did not match, the sense of the `matches' is inverted
  11415. using the `!' operator. `fcount' is incremented with the value of
  11416. `matches', which will be either one or zero, depending upon a
  11417. successful or unsuccessful match.  If the line did not match, the
  11418. `next' statement just moves on to the next record.
  11419.  
  11420.    There are several optimizations for performance in the following few
  11421. lines of code. If the user only wants exit status (`no_print' is true),
  11422. and we don't have to count lines, then it is enough to know that one
  11423. line in this file matched, and we can skip on to the next file with
  11424. `nextfile'.  Along similar lines, if we are only printing file names,
  11425. and we don't need to count lines, we can print the file name, and then
  11426. skip to the next file with `nextfile'.
  11427.  
  11428.    Finally, each line is printed, with a leading filename and colon if
  11429. necessary.
  11430.  
  11431.      {
  11432.          matches = ($0 ~ pattern)
  11433.          if (invert)
  11434.              matches = ! matches
  11435.      
  11436.          fcount += matches    # 1 or 0
  11437.      
  11438.          if (! matches)
  11439.              next
  11440.      
  11441.          if (no_print && ! count_only)
  11442.              nextfile
  11443.      
  11444.          if (filenames_only && ! count_only) {
  11445.              print FILENAME
  11446.              nextfile
  11447.          }
  11448.      
  11449.          if (do_filenames && ! count_only)
  11450.              print FILENAME ":" $0
  11451.          else if (! count_only)
  11452.              print
  11453.      }
  11454.  
  11455.    The `END' rule takes care of producing the correct exit status. If
  11456. there were no matches, the exit status is one, otherwise it is zero.
  11457.  
  11458.      END    \
  11459.      {
  11460.          if (total == 0)
  11461.              exit 1
  11462.          exit 0
  11463.      }
  11464.  
  11465.    The `usage' function prints a usage message in case of invalid
  11466. options and then exits.
  11467.  
  11468.      function usage(    e)
  11469.      {
  11470.          e = "Usage: egrep [-csvil] [-e pat] [files ...]"
  11471.          print e > "/dev/stderr"
  11472.          exit 1
  11473.      }
  11474.  
  11475.    The variable `e' is used so that the function fits nicely on the
  11476. printed page.
  11477.  
  11478. 
  11479. File: gawk.info,  Node: Id Program,  Next: Split Program,  Prev: Egrep Program,  Up: Clones
  11480.  
  11481. Printing Out User Information
  11482. -----------------------------
  11483.  
  11484.    The `id' utility lists a user's real and effective user-id numbers,
  11485. real and effective group-id numbers, and the user's group set, if any.
  11486. `id' will only print the effective user-id and group-id if they are
  11487. different from the real ones.  If possible, `id' will also supply the
  11488. corresponding user and group names.  The output might look like this:
  11489.  
  11490.      $ id
  11491.      -| uid=2076(arnold) gid=10(staff) groups=10(staff),4(tty)
  11492.  
  11493.    This information is exactly what is provided by `gawk''s `/dev/user'
  11494. special file (*note Special File Names in `gawk': Special Files.).
  11495. However, the `id' utility provides a more palatable output than just a
  11496. string of numbers.
  11497.  
  11498.    Here is a simple version of `id' written in `awk'.  It uses the user
  11499. database library functions (*note Reading the User Database: Passwd
  11500. Functions.), and the group database library functions (*note Reading
  11501. the Group Database: Group Functions.).
  11502.  
  11503.    The program is fairly straightforward.  All the work is done in the
  11504. `BEGIN' rule.  The user and group id numbers are obtained from
  11505. `/dev/user'.  If there is no support for `/dev/user', the program gives
  11506. up.
  11507.  
  11508.    The code is repetitive.  The entry in the user database for the real
  11509. user-id number is split into parts at the `:'. The name is the first
  11510. field.  Similar code is used for the effective user-id number, and the
  11511. group numbers.
  11512.  
  11513.      # id.awk --- implement id in awk
  11514.      # Arnold Robbins, arnold@gnu.ai.mit.edu, Public Domain
  11515.      # May 1993
  11516.      
  11517.      # output is:
  11518.      # uid=12(foo) euid=34(bar) gid=3(baz) \
  11519.      #             egid=5(blat) groups=9(nine),2(two),1(one)
  11520.      
  11521.      BEGIN    \
  11522.      {
  11523.          if ((getline < "/dev/user") < 0) {
  11524.              err = "id: no /dev/user support - cannot run"
  11525.              print err > "/dev/stderr"
  11526.              exit 1
  11527.          }
  11528.          close("/dev/user")
  11529.      
  11530.          uid = $1
  11531.          euid = $2
  11532.          gid = $3
  11533.          egid = $4
  11534.      
  11535.          printf("uid=%d", uid)
  11536.          pw = getpwuid(uid)
  11537.          if (pw != "") {
  11538.              split(pw, a, ":")
  11539.              printf("(%s)", a[1])
  11540.          }
  11541.      
  11542.          if (euid != uid) {
  11543.              printf(" euid=%d", euid)
  11544.              pw = getpwuid(euid)
  11545.              if (pw != "") {
  11546.                  split(pw, a, ":")
  11547.                  printf("(%s)", a[1])
  11548.              }
  11549.          }
  11550.      
  11551.          printf(" gid=%d", gid)
  11552.          pw = getgrgid(gid)
  11553.          if (pw != "") {
  11554.              split(pw, a, ":")
  11555.              printf("(%s)", a[1])
  11556.          }
  11557.      
  11558.          if (egid != gid) {
  11559.              printf(" egid=%d", egid)
  11560.              pw = getgrgid(egid)
  11561.              if (pw != "") {
  11562.                  split(pw, a, ":")
  11563.                  printf("(%s)", a[1])
  11564.              }
  11565.          }
  11566.      
  11567.          if (NF > 4) {
  11568.              printf(" groups=");
  11569.              for (i = 5; i <= NF; i++) {
  11570.                  printf("%d", $i)
  11571.                  pw = getgrgid($i)
  11572.                  if (pw != "") {
  11573.                      split(pw, a, ":")
  11574.                      printf("(%s)", a[1])
  11575.                  }
  11576.                  if (i < NF)
  11577.                      printf(",")
  11578.              }
  11579.          }
  11580.          print ""
  11581.      }
  11582.  
  11583. 
  11584. File: gawk.info,  Node: Split Program,  Next: Tee Program,  Prev: Id Program,  Up: Clones
  11585.  
  11586. Splitting a Large File Into Pieces
  11587. ----------------------------------
  11588.  
  11589.    The `split' program splits large text files into smaller pieces. By
  11590. default, the output files are named `xaa', `xab', and so on. Each file
  11591. has 1000 lines in it, with the likely exception of the last file. To
  11592. change the number of lines in each file, you supply a number on the
  11593. command line preceded with a minus, e.g., `-500' for files with 500
  11594. lines in them instead of 1000.  To change the name of the output files
  11595. to something like `myfileaa', `myfileab', and so on, you supply an
  11596. additional argument that specifies the filename.
  11597.  
  11598.    Here is a version of `split' in `awk'. It uses the `ord' and `chr'
  11599. functions presented in *Note Translating Between Characters and
  11600. Numbers: Ordinal Functions.
  11601.  
  11602.    The program first sets its defaults, and then tests to make sure
  11603. there are not too many arguments.  It then looks at each argument in
  11604. turn.  The first argument could be a minus followed by a number. If it
  11605. is, this happens to look like a negative number, so it is made
  11606. positive, and that is the count of lines.  The data file name is
  11607. skipped over, and the final argument is used as the prefix for the
  11608. output file names.
  11609.  
  11610.      # split.awk --- do split in awk
  11611.      # Arnold Robbins, arnold@gnu.ai.mit.edu, Public Domain
  11612.      # May 1993
  11613.      
  11614.      # usage: split [-num] [file] [outname]
  11615.      
  11616.      BEGIN    \
  11617.      {
  11618.          outfile = "x"    # default
  11619.          count = 1000
  11620.          if (ARGC > 4)
  11621.              usage()
  11622.      
  11623.          i = 1
  11624.          if (ARGV[i] ~ /^-[0-9]+$/) {
  11625.              count = -ARGV[i]
  11626.              ARGV[i] = ""
  11627.              i++
  11628.          }
  11629.          # test argv in case reading from stdin instead of file
  11630.          if (i in ARGV)
  11631.              i++    # skip data file name
  11632.          if (i in ARGV) {
  11633.              outfile = ARGV[i]
  11634.              ARGV[i] = ""
  11635.          }
  11636.      
  11637.          s1 = s2 = "a"
  11638.          out = (outfile s1 s2)
  11639.      }
  11640.  
  11641.    The next rule does most of the work. `tcount' (temporary count)
  11642. tracks how many lines have been printed to the output file so far. If
  11643. it is greater than `count', it is time to close the current file and
  11644. start a new one.  `s1' and `s2' track the current suffixes for the file
  11645. name. If they are both `z', the file is just too big.  Otherwise, `s1'
  11646. moves to the next letter in the alphabet and `s2' starts over again at
  11647. `a'.
  11648.  
  11649.      {
  11650.          if (++tcount > count) {
  11651.              close(out)
  11652.              if (s2 == "z") {
  11653.                  if (s1 == "z") {
  11654.                      printf("split: %s is too large to split\n", \
  11655.                             FILENAME) > "/dev/stderr"
  11656.                      exit 1
  11657.                  }
  11658.                  s1 = chr(ord(s1) + 1)
  11659.                  s2 = "a"
  11660.              } else
  11661.                  s2 = chr(ord(s2) + 1)
  11662.              out = (outfile s1 s2)
  11663.              tcount = 1
  11664.          }
  11665.          print > out
  11666.      }
  11667.  
  11668.    The `usage' function simply prints an error message and exits.
  11669.  
  11670.      function usage(   e)
  11671.      {
  11672.          e = "usage: split [-num] [file] [outname]"
  11673.          print e > "/dev/stderr"
  11674.          exit 1
  11675.      }
  11676.  
  11677. The variable `e' is used so that the function fits nicely on the screen.
  11678.  
  11679.    This program is a bit sloppy; it relies on `awk' to close the last
  11680. file for it automatically, instead of doing it in an `END' rule.
  11681.  
  11682. 
  11683. File: gawk.info,  Node: Tee Program,  Next: Uniq Program,  Prev: Split Program,  Up: Clones
  11684.  
  11685. Duplicating Output Into Multiple Files
  11686. --------------------------------------
  11687.  
  11688.    The `tee' program is known as a "pipe fitting."  `tee' copies its
  11689. standard input to its standard output, and also duplicates it to the
  11690. files named on the command line.  Its usage is:
  11691.  
  11692.      tee [-a] file ...
  11693.  
  11694.    The `-a' option tells `tee' to append to the named files, instead of
  11695. truncating them and starting over.
  11696.  
  11697.    The `BEGIN' rule first makes a copy of all the command line
  11698. arguments, into an array named `copy'.  `ARGV[0]' is not copied, since
  11699. it is not needed.  `tee' cannot use `ARGV' directly, since `awk' will
  11700. attempt to process each file named in `ARGV' as input data.
  11701.  
  11702.    If the first argument is `-a', then the flag variable `append' is
  11703. set to true, and both `ARGV[1]' and `copy[1]' are deleted. If `ARGC' is
  11704. less than two, then no file names were supplied, and `tee' prints a
  11705. usage message and exits.  Finally, `awk' is forced to read the standard
  11706. input by setting `ARGV[1]' to `"-"', and `ARGC' to two.
  11707.  
  11708.      # tee.awk --- tee in awk
  11709.      # Arnold Robbins, arnold@gnu.ai.mit.edu, Public Domain
  11710.      # May 1993
  11711.      # Revised December 1995
  11712.      
  11713.      BEGIN    \
  11714.      {
  11715.          for (i = 1; i < ARGC; i++)
  11716.              copy[i] = ARGV[i]
  11717.      
  11718.          if (ARGV[1] == "-a") {
  11719.              append = 1
  11720.              delete ARGV[1]
  11721.              delete copy[1]
  11722.              ARGC--
  11723.          }
  11724.          if (ARGC < 2) {
  11725.              print "usage: tee [-a] file ..." > "/dev/stderr"
  11726.              exit 1
  11727.          }
  11728.          ARGV[1] = "-"
  11729.          ARGC = 2
  11730.      }
  11731.  
  11732.    The single rule does all the work.  Since there is no pattern, it is
  11733. executed for each line of input.  The body of the rule simply prints the
  11734. line into each file on the command line, and then to the standard
  11735. output.
  11736.  
  11737.      {
  11738.          # moving the if outside the loop makes it run faster
  11739.          if (append)
  11740.              for (i in copy)
  11741.                  print >> copy[i]
  11742.          else
  11743.              for (i in copy)
  11744.                  print > copy[i]
  11745.          print
  11746.      }
  11747.  
  11748.    It would have been possible to code the loop this way:
  11749.  
  11750.      for (i in copy)
  11751.          if (append)
  11752.              print >> copy[i]
  11753.          else
  11754.              print > copy[i]
  11755.  
  11756. This is more concise, but it is also less efficient.  The `if' is
  11757. tested for each record and for each output file.  By duplicating the
  11758. loop body, the `if' is only tested once for each input record.  If
  11759. there are N input records and M input files, the first method only
  11760. executes N `if' statements, while the second would execute N`*'M `if'
  11761. statements.
  11762.  
  11763.    Finally, the `END' rule cleans up, by closing all the output files.
  11764.  
  11765.      END    \
  11766.      {
  11767.          for (i in copy)
  11768.              close(copy[i])
  11769.      }
  11770.  
  11771. 
  11772. File: gawk.info,  Node: Uniq Program,  Next: Wc Program,  Prev: Tee Program,  Up: Clones
  11773.  
  11774. Printing Non-duplicated Lines of Text
  11775. -------------------------------------
  11776.  
  11777.    The `uniq' utility reads sorted lines of data on its standard input,
  11778. and (by default) removes duplicate lines.  In other words, only unique
  11779. lines are printed, hence the name.  `uniq' has a number of options. The
  11780. usage is:
  11781.  
  11782.      uniq [-udc [-N]] [+N] [ INPUT FILE [ OUTPUT FILE ]]
  11783.  
  11784.    The option meanings are:
  11785.  
  11786. `-d'
  11787.      Only print repeated lines.
  11788.  
  11789. `-u'
  11790.      Only print non-repeated lines.
  11791.  
  11792. `-c'
  11793.      Count lines. This option overrides `-d' and `-u'.  Both repeated
  11794.      and non-repeated lines are counted.
  11795.  
  11796. `-N'
  11797.      Skip N fields before comparing lines.  The definition of fields is
  11798.      the same as `awk''s default: non-whitespace characters separated
  11799.      by runs of spaces and/or tabs.
  11800.  
  11801. `+N'
  11802.      Skip N characters before comparing lines.  Any fields specified
  11803.      with `-N' are skipped first.
  11804.  
  11805. `INPUT FILE'
  11806.      Data is read from the input file named on the command line,
  11807.      instead of from the standard input.
  11808.  
  11809. `OUTPUT FILE'
  11810.      The generated output is sent to the named output file, instead of
  11811.      to the standard output.
  11812.  
  11813.    Normally `uniq' behaves as if both the `-d' and `-u' options had
  11814. been provided.
  11815.  
  11816.    Here is an `awk' implementation of `uniq'. It uses the `getopt'
  11817. library function (*note Processing Command Line Options: Getopt
  11818. Function.), and the `join' library function (*note Merging an Array
  11819. Into a String: Join Function.).
  11820.  
  11821.    The program begins with a `usage' function and then a brief outline
  11822. of the options and their meanings in a comment.
  11823.  
  11824.    The `BEGIN' rule deals with the command line arguments and options.
  11825. It uses a trick to get `getopt' to handle options of the form `-25',
  11826. treating such an option as the option letter `2' with an argument of
  11827. `5'. If indeed two or more digits were supplied (`Optarg' looks like a
  11828. number), `Optarg' is concatenated with the option digit, and then
  11829. result is added to zero to make it into a number.  If there is only one
  11830. digit in the option, then `Optarg' is not needed, and `Optind' must be
  11831. decremented so that `getopt' will process it next time.  This code is
  11832. admittedly a bit tricky.
  11833.  
  11834.    If no options were supplied, then the default is taken, to print both
  11835. repeated and non-repeated lines.  The output file, if provided, is
  11836. assigned to `outputfile'.  Earlier, `outputfile' was initialized to the
  11837. standard output, `/dev/stdout'.
  11838.  
  11839.      # uniq.awk --- do uniq in awk
  11840.      # Arnold Robbins, arnold@gnu.ai.mit.edu, Public Domain
  11841.      # May 1993
  11842.      
  11843.      function usage(    e)
  11844.      {
  11845.          e = "Usage: uniq [-udc [-n]] [+n] [ in [ out ]]"
  11846.          print e > "/dev/stderr"
  11847.          exit 1
  11848.      }
  11849.      
  11850.      # -c    count lines. overrides -d and -u
  11851.      # -d    only repeated lines
  11852.      # -u    only non-repeated lines
  11853.      # -n    skip n fields
  11854.      # +n    skip n characters, skip fields first
  11855.      
  11856.      BEGIN    \
  11857.      {
  11858.          count = 1
  11859.          outputfile = "/dev/stdout"
  11860.          opts = "udc0:1:2:3:4:5:6:7:8:9:"
  11861.          while ((c = getopt(ARGC, ARGV, opts)) != -1) {
  11862.              if (c == "u")
  11863.                  non_repeated_only++
  11864.              else if (c == "d")
  11865.                  repeated_only++
  11866.              else if (c == "c")
  11867.                  do_count++
  11868.              else if (index("0123456789", c) != 0) {
  11869.                  # getopt requires args to options
  11870.                  # this messes us up for things like -5
  11871.                  if (Optarg ~ /^[0-9]+$/)
  11872.                      fcount = (c Optarg) + 0
  11873.                  else {
  11874.                      fcount = c + 0
  11875.                      Optind--
  11876.                  }
  11877.              } else
  11878.                  usage()
  11879.          }
  11880.      
  11881.          if (ARGV[Optind] ~ /^\+[0-9]+$/) {
  11882.              charcount = substr(ARGV[Optind], 2) + 0
  11883.              Optind++
  11884.          }
  11885.      
  11886.          for (i = 1; i < Optind; i++)
  11887.              ARGV[i] = ""
  11888.      
  11889.          if (repeated_only == 0 && non_repeated_only == 0)
  11890.              repeated_only = non_repeated_only = 1
  11891.      
  11892.          if (ARGC - Optind == 2) {
  11893.              outputfile = ARGV[ARGC - 1]
  11894.              ARGV[ARGC - 1] = ""
  11895.          }
  11896.      }
  11897.  
  11898.    The following function, `are_equal', compares the current line,
  11899. `$0', to the previous line, `last'.  It handles skipping fields and
  11900. characters.
  11901.  
  11902.    If no field count and no character count were specified, `are_equal'
  11903. simply returns one or zero depending upon the result of a simple string
  11904. comparison of `last' and `$0'.  Otherwise, things get more complicated.
  11905.  
  11906.    If fields have to be skipped, each line is broken into an array using
  11907. `split' (*note Built-in Functions for String Manipulation: String
  11908. Functions.), and then the desired fields are joined back into a line
  11909. using `join'.  The joined lines are stored in `clast' and `cline'.  If
  11910. no fields are skipped, `clast' and `cline' are set to `last' and `$0'
  11911. respectively.
  11912.  
  11913.    Finally, if characters are skipped, `substr' is used to strip off the
  11914. leading `charcount' characters in `clast' and `cline'.  The two strings
  11915. are then compared, and `are_equal' returns the result.
  11916.  
  11917.      function are_equal(    n, m, clast, cline, alast, aline)
  11918.      {
  11919.          if (fcount == 0 && charcount == 0)
  11920.              return (last == $0)
  11921.      
  11922.          if (fcount > 0) {
  11923.              n = split(last, alast)
  11924.              m = split($0, aline)
  11925.              clast = join(alast, fcount+1, n)
  11926.              cline = join(aline, fcount+1, m)
  11927.          } else {
  11928.              clast = last
  11929.              cline = $0
  11930.          }
  11931.          if (charcount) {
  11932.              clast = substr(clast, charcount + 1)
  11933.              cline = substr(cline, charcount + 1)
  11934.          }
  11935.      
  11936.          return (clast == cline)
  11937.      }
  11938.  
  11939.    The following two rules are the body of the program.  The first one
  11940. is executed only for the very first line of data.  It sets `last' equal
  11941. to `$0', so that subsequent lines of text have something to be compared
  11942. to.
  11943.  
  11944.    The second rule does the work. The variable `equal' will be one or
  11945. zero depending upon the results of `are_equal''s comparison. If `uniq'
  11946. is counting repeated lines, then the `count' variable is incremented if
  11947. the lines are equal. Otherwise the line is printed and `count' is
  11948. reset, since the two lines are not equal.
  11949.  
  11950.    If `uniq' is not counting, `count' is incremented if the lines are
  11951. equal. Otherwise, if `uniq' is counting repeated lines, and more than
  11952. one line has been seen, or if `uniq' is counting non-repeated lines,
  11953. and only one line has been seen, then the line is printed, and `count'
  11954. is reset.
  11955.  
  11956.    Finally, similar logic is used in the `END' rule to print the final
  11957. line of input data.
  11958.  
  11959.      NR == 1 {
  11960.          last = $0
  11961.          next
  11962.      }
  11963.      
  11964.      {
  11965.          equal = are_equal()
  11966.      
  11967.          if (do_count) {    # overrides -d and -u
  11968.              if (equal)
  11969.                  count++
  11970.              else {
  11971.                  printf("%4d %s\n", count, last) > outputfile
  11972.                  last = $0
  11973.                  count = 1    # reset
  11974.              }
  11975.              next
  11976.          }
  11977.      
  11978.          if (equal)
  11979.              count++
  11980.          else {
  11981.              if ((repeated_only && count > 1) ||
  11982.                  (non_repeated_only && count == 1))
  11983.                      print last > outputfile
  11984.              last = $0
  11985.              count = 1
  11986.          }
  11987.      }
  11988.      
  11989.      END {
  11990.          if (do_count)
  11991.              printf("%4d %s\n", count, last) > outputfile
  11992.          else if ((repeated_only && count > 1) ||
  11993.                  (non_repeated_only && count == 1))
  11994.              print last > outputfile
  11995.      }
  11996.  
  11997. 
  11998. File: gawk.info,  Node: Wc Program,  Prev: Uniq Program,  Up: Clones
  11999.  
  12000. Counting Things
  12001. ---------------
  12002.  
  12003.    The `wc' (word count) utility counts lines, words, and characters in
  12004. one or more input files. Its usage is:
  12005.  
  12006.      wc [-lwc] [ FILES ... ]
  12007.  
  12008.    If no files are specified on the command line, `wc' reads its
  12009. standard input. If there are multiple files, it will also print total
  12010. counts for all the files.  The options and their meanings are:
  12011.  
  12012. `-l'
  12013.      Only count lines.
  12014.  
  12015. `-w'
  12016.      Only count words.  A "word" is a contiguous sequence of
  12017.      non-whitespace characters, separated by spaces and/or tabs.
  12018.      Happily, this is the normal way `awk' separates fields in its
  12019.      input data.
  12020.  
  12021. `-c'
  12022.      Only count characters.
  12023.  
  12024.    Implementing `wc' in `awk' is particularly elegant, since `awk' does
  12025. a lot of the work for us; it splits lines into words (i.e.  fields) and
  12026. counts them, it counts lines (i.e. records) for us, and it can easily
  12027. tell us how long a line is.
  12028.  
  12029.    This version uses the `getopt' library function (*note Processing
  12030. Command Line Options: Getopt Function.), and the file transition
  12031. functions (*note Noting Data File Boundaries: Filetrans Function.).
  12032.  
  12033.    This version has one major difference from traditional versions of
  12034. `wc'.  Our version always prints the counts in the order lines, words,
  12035. and characters.  Traditional versions note the order of the `-l', `-w',
  12036. and `-c' options on the command line, and print the counts in that
  12037. order.
  12038.  
  12039.    The `BEGIN' rule does the argument processing.  The variable
  12040. `print_total' will be true if more than one file was named on the
  12041. command line.
  12042.  
  12043.      # wc.awk --- count lines, words, characters
  12044.      # Arnold Robbins, arnold@gnu.ai.mit.edu, Public Domain
  12045.      # May 1993
  12046.      
  12047.      # Options:
  12048.      #    -l    only count lines
  12049.      #    -w    only count words
  12050.      #    -c    only count characters
  12051.      #
  12052.      # Default is to count lines, words, characters
  12053.      
  12054.      BEGIN {
  12055.          # let getopt print a message about
  12056.          # invalid options. we ignore them
  12057.          while ((c = getopt(ARGC, ARGV, "lwc")) != -1) {
  12058.              if (c == "l")
  12059.                  do_lines = 1
  12060.              else if (c == "w")
  12061.                  do_words = 1
  12062.              else if (c == "c")
  12063.                  do_chars = 1
  12064.          }
  12065.          for (i = 1; i < Optind; i++)
  12066.              ARGV[i] = ""
  12067.      
  12068.          # if no options, do all
  12069.          if (! do_lines && ! do_words && ! do_chars)
  12070.              do_lines = do_words = do_chars = 1
  12071.      
  12072.          print_total = (ARC - i > 2)
  12073.      }
  12074.  
  12075.    The `beginfile' function is simple; it just resets the counts of
  12076. lines, words, and characters to zero, and saves the current file name in
  12077. `fname'.
  12078.  
  12079.    The `endfile' function adds the current file's numbers to the running
  12080. totals of lines, words, and characters.  It then prints out those
  12081. numbers for the file that was just read. It relies on `beginfile' to
  12082. reset the numbers for the following data file.
  12083.  
  12084.      function beginfile(file)
  12085.      {
  12086.          chars = lines = words = 0
  12087.          fname = FILENAME
  12088.      }
  12089.      
  12090.      function endfile(file)
  12091.      {
  12092.          tchars += chars
  12093.          tlines += lines
  12094.          twords += words
  12095.          if (do_lines)
  12096.              printf "\t%d", lines
  12097.          if (do_words)
  12098.              printf "\t%d", words
  12099.          if (do_chars)
  12100.              printf "\t%d", chars
  12101.          printf "\t%s\n", fname
  12102.      }
  12103.  
  12104.    There is one rule that is executed for each line. It adds the length
  12105. of the record to `chars'.  It has to add one, since the newline
  12106. character separating records (the value of `RS') is not part of the
  12107. record itself.  `lines' is incremented for each line read, and `words'
  12108. is incremented by the value of `NF', the number of "words" on this
  12109. line.(1)
  12110.  
  12111.    Finally, the `END' rule simply prints the totals for all the files.
  12112.  
  12113.      # do per line
  12114.      {
  12115.          chars += length($0) + 1    # get newline
  12116.          lines++
  12117.          words += NF
  12118.      }
  12119.      
  12120.      END {
  12121.          if (print_total) {
  12122.              if (do_lines)
  12123.                  printf "\t%d", tlines
  12124.              if (do_words)
  12125.                  printf "\t%d", twords
  12126.              if (do_chars)
  12127.                  printf "\t%d", tchars
  12128.              print "\ttotal"
  12129.          }
  12130.      }
  12131.  
  12132.    ---------- Footnotes ----------
  12133.  
  12134.    (1)  Examine the code in *Note Noting Data File Boundaries:
  12135. Filetrans Function.  Why must `wc' use a separate `lines' variable,
  12136. instead of using the value of `FNR' in `endfile'?
  12137.  
  12138. 
  12139. File: gawk.info,  Node: Miscellaneous Programs,  Prev: Clones,  Up: Sample Programs
  12140.  
  12141. A Grab Bag of `awk' Programs
  12142. ============================
  12143.  
  12144.    This section is a large "grab bag" of miscellaneous programs.  We
  12145. hope you find them both interesting and enjoyable.
  12146.  
  12147. * Menu:
  12148.  
  12149. * Dupword Program::         Finding duplicated words in a document.
  12150. * Alarm Program::           An alarm clock.
  12151. * Translate Program::       A program similar to the `tr' utility.
  12152. * Labels Program::          Printing mailing labels.
  12153. * Word Sorting::            A program to produce a word usage count.
  12154. * History Sorting::         Eliminating duplicate entries from a history
  12155.                             file.
  12156. * Extract Program::         Pulling out programs from Texinfo source
  12157.                             files.
  12158. * Simple Sed::              A Simple Stream Editor.
  12159. * Igawk Program::           A wrapper for `awk' that includes files.
  12160.  
  12161. 
  12162. File: gawk.info,  Node: Dupword Program,  Next: Alarm Program,  Prev: Miscellaneous Programs,  Up: Miscellaneous Programs
  12163.  
  12164. Finding Duplicated Words in a Document
  12165. --------------------------------------
  12166.  
  12167.    A common error when writing large amounts of prose is to accidentally
  12168. duplicate words.  Often you will see this in text as something like "the
  12169. the program does the following ...."  When the text is on-line, often
  12170. the duplicated words occur at the end of one line and the beginning of
  12171. another, making them very difficult to spot.
  12172.  
  12173.    This program, `dupword.awk', scans through a file one line at a time,
  12174. and looks for adjacent occurrences of the same word.  It also saves the
  12175. last word on a line (in the variable `prev') for comparison with the
  12176. first word on the next line.
  12177.  
  12178.    The first two statements make sure that the line is all lower-case,
  12179. so that, for example, "The" and "the" compare equal to each other.  The
  12180. second statement removes all non-alphanumeric and non-whitespace
  12181. characters from the line, so that punctuation does not affect the
  12182. comparison either.  This sometimes leads to reports of duplicated words
  12183. that really are different, but this is unusual.
  12184.  
  12185.      # dupword --- find duplicate words in text
  12186.      # Arnold Robbins, arnold@gnu.ai.mit.edu, Public Domain
  12187.      # December 1991
  12188.      
  12189.      {
  12190.          $0 = tolower($0)
  12191.          gsub(/[^A-Za-z0-9 \t]/, "");
  12192.          if ($1 == prev)
  12193.              printf("%s:%d: duplicate %s\n",
  12194.                  FILENAME, FNR, $1)
  12195.          for (i = 2; i <= NF; i++)
  12196.              if ($i == $(i-1))
  12197.                  printf("%s:%d: duplicate %s\n",
  12198.                      FILENAME, FNR, $i)
  12199.          prev = $NF
  12200.      }
  12201.  
  12202. 
  12203. File: gawk.info,  Node: Alarm Program,  Next: Translate Program,  Prev: Dupword Program,  Up: Miscellaneous Programs
  12204.  
  12205. An Alarm Clock Program
  12206. ----------------------
  12207.  
  12208.    The following program is a simple "alarm clock" program.  You give
  12209. it a time of day, and an optional message.  At the given time, it
  12210. prints the message on the standard output. In addition, you can give it
  12211. the number of times to repeat the message, and also a delay between
  12212. repetitions.
  12213.  
  12214.    This program uses the `gettimeofday' function from *Note Managing
  12215. the Time of Day: Gettimeofday Function.
  12216.  
  12217.    All the work is done in the `BEGIN' rule.  The first part is argument
  12218. checking and setting of defaults; the delay, the count, and the message
  12219. to print.  If the user supplied a message, but it does not contain the
  12220. ASCII BEL character (known as the "alert" character, `\a'), then it is
  12221. added to the message.  (On many systems, printing the ASCII BEL
  12222. generates some sort of audible alert. Thus, when the alarm goes off,
  12223. the system calls attention to itself, in case the user is not looking
  12224. at their computer or terminal.)
  12225.  
  12226.      # alarm --- set an alarm
  12227.      # Arnold Robbins, arnold@gnu.ai.mit.edu, Public Domain
  12228.      # May 1993
  12229.      
  12230.      # usage: alarm time [ "message" [ count [ delay ] ] ]
  12231.      
  12232.      BEGIN    \
  12233.      {
  12234.          # Initial argument sanity checking
  12235.          usage1 = "usage: alarm time ['message' [count [delay]]]"
  12236.          usage2 = sprintf("\t(%s) time ::= hh:mm", ARGV[1])
  12237.      
  12238.          if (ARGC < 2) {
  12239.              print usage > "/dev/stderr"
  12240.              exit 1
  12241.          } else if (ARGC == 5) {
  12242.              delay = ARGV[4] + 0
  12243.              count = ARGV[3] + 0
  12244.              message = ARGV[2]
  12245.          } else if (ARGC == 4) {
  12246.              count = ARGV[3] + 0
  12247.              message = ARGV[2]
  12248.          } else if (ARGC == 3) {
  12249.              message = ARGV[2]
  12250.          } else if (ARGV[1] !~ /[0-9]?[0-9]:[0-9][0-9]/) {
  12251.              print usage1 > "/dev/stderr"
  12252.              print usage2 > "/dev/stderr"
  12253.              exit 1
  12254.          }
  12255.      
  12256.          # set defaults for once we reach the desired time
  12257.          if (delay == 0)
  12258.              delay = 180    # 3 minutes
  12259.          if (count == 0)
  12260.              count = 5
  12261.          if (message == "")
  12262.              message = sprintf("\aIt is now %s!\a", ARGV[1])
  12263.          else if (index(message, "\a") == 0)
  12264.              message = "\a" message "\a"
  12265.  
  12266.    The next section of code turns the alarm time into hours and minutes,
  12267. and converts it if necessary to a 24-hour clock.  Then it turns that
  12268. time into a count of the seconds since midnight.  Next it turns the
  12269. current time into a count of seconds since midnight.  The difference
  12270. between the two is how long to wait before setting off the alarm.
  12271.  
  12272.          # split up dest time
  12273.          split(ARGV[1], atime, ":")
  12274.          hour = atime[1] + 0    # force numeric
  12275.          minute = atime[2] + 0  # force numeric
  12276.      
  12277.          # get current broken down time
  12278.          gettimeofday(now)
  12279.      
  12280.          # if time given is 12-hour hours and it's after that
  12281.          # hour, e.g., `alarm 5:30' at 9 a.m. means 5:30 p.m.,
  12282.          # then add 12 to real hour
  12283.          if (hour < 12 && now["hour"] > hour)
  12284.              hour += 12
  12285.      
  12286.          # set target time in seconds since midnight
  12287.          target = (hour * 60 * 60) + (minute * 60)
  12288.      
  12289.          # get current time in seconds since midnight
  12290.          current = (now["hour"] * 60 * 60) + \
  12291.                     (now["minute"] * 60) + now["second"]
  12292.      
  12293.          # how long to sleep for
  12294.          naptime = target - current
  12295.          if (naptime <= 0) {
  12296.              print "time is in the past!" > "/dev/stderr"
  12297.              exit 1
  12298.          }
  12299.  
  12300.    Finally, the program uses the `system' function (*note Built-in
  12301. Functions for Input/Output: I/O Functions.) to call the `sleep'
  12302. utility.  The `sleep' utility simply pauses for the given number of
  12303. seconds.  If the exit status is not zero, the program assumes that
  12304. `sleep' was interrupted, and exits. If `sleep' exited with an OK status
  12305. (zero), then the program prints the message in a loop, again using
  12306. `sleep' to delay for however many seconds are necessary.
  12307.  
  12308.          # zzzzzz..... go away if interrupted
  12309.          if (system(sprintf("sleep %d", naptime)) != 0)
  12310.              exit 1
  12311.      
  12312.          # time to notify!
  12313.          command = sprintf("sleep %d", delay)
  12314.          for (i = 1; i <= count; i++) {
  12315.              print message
  12316.              # if sleep command interrupted, go away
  12317.              if (system(command) != 0)
  12318.                  break
  12319.          }
  12320.      
  12321.          exit 0
  12322.      }
  12323.  
  12324. 
  12325. File: gawk.info,  Node: Translate Program,  Next: Labels Program,  Prev: Alarm Program,  Up: Miscellaneous Programs
  12326.  
  12327. Transliterating Characters
  12328. --------------------------
  12329.  
  12330.    The system `tr' utility transliterates characters.  For example, it
  12331. is often used to map upper-case letters into lower-case, for further
  12332. processing.
  12333.  
  12334.      GENERATE DATA | tr '[A-Z]' '[a-z]' | PROCESS DATA ...
  12335.  
  12336.    You give `tr' two lists of characters enclosed in square brackets.
  12337. Usually, the lists are quoted to keep the shell from attempting to do a
  12338. filename expansion.(1)  When processing the input, the first character
  12339. in the first list is replaced with the first character in the second
  12340. list, the second character in the first list is replaced with the
  12341. second character in the second list, and so on.  If there are more
  12342. characters in the "from" list than in the "to" list, the last character
  12343. of the "to" list is used for the remaining characters in the "from"
  12344. list.
  12345.  
  12346.    Some time ago, a user proposed to us that we add a transliteration
  12347. function to `gawk'.  Being opposed to "creeping featurism," I wrote the
  12348. following program to prove that character transliteration could be done
  12349. with a user-level function.  This program is not as complete as the
  12350. system `tr' utility, but it will do most of the job.
  12351.  
  12352.    The `translate' program demonstrates one of the few weaknesses of
  12353. standard `awk': dealing with individual characters is very painful,
  12354. requiring repeated use of the `substr', `index', and `gsub' built-in
  12355. functions (*note Built-in Functions for String Manipulation: String
  12356. Functions.).(2)
  12357.  
  12358.    There are two functions.  The first, `stranslate', takes three
  12359. arguments.
  12360.  
  12361. `from'
  12362.      A list of characters to translate from.
  12363.  
  12364. `to'
  12365.      A list of characters to translate to.
  12366.  
  12367. `target'
  12368.      The string to do the translation on.
  12369.  
  12370.    Associative arrays make the translation part fairly easy. `t_ar'
  12371. holds the "to" characters, indexed by the "from" characters.  Then a
  12372. simple loop goes through `from', one character at a time.  For each
  12373. character in `from', if the character appears in `target', `gsub' is
  12374. used to change it to the corresponding `to' character.
  12375.  
  12376.    The `translate' function simply calls `stranslate' using `$0' as the
  12377. target.  The main program sets two global variables, `FROM' and `TO',
  12378. from the command line, and then changes `ARGV' so that `awk' will read
  12379. from the standard input.
  12380.  
  12381.    Finally, the processing rule simply calls `translate' for each
  12382. record.
  12383.  
  12384.      # translate --- do tr like stuff
  12385.      # Arnold Robbins, arnold@gnu.ai.mit.edu, Public Domain
  12386.      # August 1989
  12387.      
  12388.      # bugs: does not handle things like: tr A-Z a-z, it has
  12389.      # to be spelled out. However, if `to' is shorter than `from',
  12390.      # the last character in `to' is used for the rest of `from'.
  12391.      
  12392.      function stranslate(from, to, target,     lf, lt, t_ar, i, c)
  12393.      {
  12394.          lf = length(from)
  12395.          lt = length(to)
  12396.          for (i = 1; i <= lt; i++)
  12397.              t_ar[substr(from, i, 1)] = substr(to, i, 1)
  12398.          if (lt < lf)
  12399.              for (; i <= lf; i++)
  12400.                  t_ar[substr(from, i, 1)] = substr(to, lt, 1)
  12401.          for (i = 1; i <= lf; i++) {
  12402.              c = substr(from, i, 1)
  12403.              if (index(target, c) > 0)
  12404.                  gsub(c, t_ar[c], target)
  12405.          }
  12406.          return target
  12407.      }
  12408.      
  12409.      function translate(from, to)
  12410.      {
  12411.          return $0 = stranslate(from, to, $0)
  12412.      }
  12413.      
  12414.      # main program
  12415.      BEGIN {
  12416.          if (ARGC < 3) {
  12417.              print "usage: translate from to" > "/dev/stderr"
  12418.              exit
  12419.          }
  12420.          FROM = ARGV[1]
  12421.          TO = ARGV[2]
  12422.          ARGC = 2
  12423.          ARGV[1] = "-"
  12424.      }
  12425.      
  12426.      {
  12427.          translate(FROM, TO)
  12428.          print
  12429.      }
  12430.  
  12431.    While it is possible to do character transliteration in a user-level
  12432. function, it is not necessarily efficient, and we started to consider
  12433. adding a built-in function.  However, shortly after writing this
  12434. program, we learned that the System V Release 4 `awk' had added the
  12435. `toupper' and `tolower' functions.  These functions handle the vast
  12436. majority of the cases where character transliteration is necessary, and
  12437. so we chose to simply add those functions to `gawk' as well, and then
  12438. leave well enough alone.
  12439.  
  12440.    An obvious improvement to this program would be to set up the `t_ar'
  12441. array only once, in a `BEGIN' rule. However, this assumes that the
  12442. "from" and "to" lists will never change throughout the lifetime of the
  12443. program.
  12444.  
  12445.    ---------- Footnotes ----------
  12446.  
  12447.    (1)  On older, non-POSIX systems, `tr' often does not require that
  12448. the lists be enclosed in square brackets and quoted.  This is a feature.
  12449.  
  12450.    (2)  This program was written before `gawk' acquired the ability to
  12451. split each character in a string into separate array elements.  How
  12452. might this ability simplify the program?
  12453.  
  12454. 
  12455. File: gawk.info,  Node: Labels Program,  Next: Word Sorting,  Prev: Translate Program,  Up: Miscellaneous Programs
  12456.  
  12457. Printing Mailing Labels
  12458. -----------------------
  12459.  
  12460.    Here is a "real world"(1) program.  This script reads lists of names
  12461. and addresses, and generates mailing labels.  Each page of labels has
  12462. 20 labels on it, two across and ten down.  The addresses are guaranteed
  12463. to be no more than five lines of data.  Each address is separated from
  12464. the next by a blank line.
  12465.  
  12466.    The basic idea is to read 20 labels worth of data.  Each line of
  12467. each label is stored in the `line' array.  The single rule takes care
  12468. of filling the `line' array and printing the page when 20 labels have
  12469. been read.
  12470.  
  12471.    The `BEGIN' rule simply sets `RS' to the empty string, so that `awk'
  12472. will split records at blank lines (*note How Input is Split into
  12473. Records: Records.).  It sets `MAXLINES' to 100, since `MAXLINE' is the
  12474. maximum number of lines on the page (20 * 5 = 100).
  12475.  
  12476.    Most of the work is done in the `printpage' function.  The label
  12477. lines are stored sequentially in the `line' array.  But they have to be
  12478. printed horizontally; `line[1]' next to `line[6]', `line[2]' next to
  12479. `line[7]', and so on.  Two loops are used to accomplish this.  The
  12480. outer loop, controlled by `i', steps through every 10 lines of data;
  12481. this is each row of labels.  The inner loop, controlled by `j', goes
  12482. through the lines within the row.  As `j' goes from zero to four, `i+j'
  12483. is the `j''th line in the row, and `i+j+5' is the entry next to it.
  12484. The output ends up looking something like this:
  12485.  
  12486.      line 1          line 6
  12487.      line 2          line 7
  12488.      line 3          line 8
  12489.      line 4          line 9
  12490.      line 5          line 10
  12491.  
  12492.    As a final note, at lines 21 and 61, an extra blank line is printed,
  12493. to keep the output lined up on the labels.  This is dependent on the
  12494. particular brand of labels in use when the program was written.  You
  12495. will also note that there are two blank lines at the top and two blank
  12496. lines at the bottom.
  12497.  
  12498.    The `END' rule arranges to flush the final page of labels; there may
  12499. not have been an even multiple of 20 labels in the data.
  12500.  
  12501.      # labels.awk
  12502.      # Arnold Robbins, arnold@gnu.ai.mit.edu, Public Domain
  12503.      # June 1992
  12504.      
  12505.      # Program to print labels.  Each label is 5 lines of data
  12506.      # that may have blank lines.  The label sheets have 2
  12507.      # blank lines at the top and 2 at the bottom.
  12508.      
  12509.      BEGIN    { RS = "" ; MAXLINES = 100 }
  12510.      
  12511.      function printpage(    i, j)
  12512.      {
  12513.          if (Nlines <= 0)
  12514.              return
  12515.      
  12516.          printf "\n\n"        # header
  12517.      
  12518.          for (i = 1; i <= Nlines; i += 10) {
  12519.              if (i == 21 || i == 61)
  12520.                  print ""
  12521.              for (j = 0; j < 5; j++) {
  12522.                  if (i + j > MAXLINES)
  12523.                      break
  12524.                  printf "   %-41s %s\n", line[i+j], line[i+j+5]
  12525.              }
  12526.              print ""
  12527.          }
  12528.      
  12529.          printf "\n\n"        # footer
  12530.      
  12531.          for (i in line)
  12532.              line[i] = ""
  12533.      }
  12534.      
  12535.      # main rule
  12536.      {
  12537.          if (Count >= 20) {
  12538.              printpage()
  12539.              Count = 0
  12540.              Nlines = 0
  12541.          }
  12542.          n = split($0, a, "\n")
  12543.          for (i = 1; i <= n; i++)
  12544.              line[++Nlines] = a[i]
  12545.          for (; i <= 5; i++)
  12546.              line[++Nlines] = ""
  12547.          Count++
  12548.      }
  12549.      
  12550.      END    \
  12551.      {
  12552.          printpage()
  12553.      }
  12554.  
  12555.    ---------- Footnotes ----------
  12556.  
  12557.    (1)  "Real world" is defined as "a program actually used to get
  12558. something done."
  12559.  
  12560. 
  12561. File: gawk.info,  Node: Word Sorting,  Next: History Sorting,  Prev: Labels Program,  Up: Miscellaneous Programs
  12562.  
  12563. Generating Word Usage Counts
  12564. ----------------------------
  12565.  
  12566.    The following `awk' program prints the number of occurrences of each
  12567. word in its input.  It illustrates the associative nature of `awk'
  12568. arrays by using strings as subscripts.  It also demonstrates the `for X
  12569. in ARRAY' construction.  Finally, it shows how `awk' can be used in
  12570. conjunction with other utility programs to do a useful task of some
  12571. complexity with a minimum of effort.  Some explanations follow the
  12572. program listing.
  12573.  
  12574.      awk '
  12575.      # Print list of word frequencies
  12576.      {
  12577.          for (i = 1; i <= NF; i++)
  12578.              freq[$i]++
  12579.      }
  12580.      
  12581.      END {
  12582.          for (word in freq)
  12583.              printf "%s\t%d\n", word, freq[word]
  12584.      }'
  12585.  
  12586.    The first thing to notice about this program is that it has two
  12587. rules.  The first rule, because it has an empty pattern, is executed on
  12588. every line of the input.  It uses `awk''s field-accessing mechanism
  12589. (*note Examining Fields: Fields.) to pick out the individual words from
  12590. the line, and the built-in variable `NF' (*note Built-in Variables::.)
  12591. to know how many fields are available.
  12592.  
  12593.    For each input word, an element of the array `freq' is incremented to
  12594. reflect that the word has been seen an additional time.
  12595.  
  12596.    The second rule, because it has the pattern `END', is not executed
  12597. until the input has been exhausted.  It prints out the contents of the
  12598. `freq' table that has been built up inside the first action.
  12599.  
  12600.    This program has several problems that would prevent it from being
  12601. useful by itself on real text files:
  12602.  
  12603.    * Words are detected using the `awk' convention that fields are
  12604.      separated by whitespace and that other characters in the input
  12605.      (except newlines) don't have any special meaning to `awk'.  This
  12606.      means that punctuation characters count as part of words.
  12607.  
  12608.    * The `awk' language considers upper- and lower-case characters to be
  12609.      distinct.  Therefore, `bartender' and `Bartender' are not treated
  12610.      as the same word.  This is undesirable since, in normal text, words
  12611.      are capitalized if they begin sentences, and a frequency analyzer
  12612.      should not be sensitive to capitalization.
  12613.  
  12614.    * The output does not come out in any useful order.  You're more
  12615.      likely to be interested in which words occur most frequently, or
  12616.      having an alphabetized table of how frequently each word occurs.
  12617.  
  12618.    The way to solve these problems is to use some of the more advanced
  12619. features of the `awk' language.  First, we use `tolower' to remove case
  12620. distinctions.  Next, we use `gsub' to remove punctuation characters.
  12621. Finally, we use the system `sort' utility to process the output of the
  12622. `awk' script.  Here is the new version of the program:
  12623.  
  12624.      # Print list of word frequencies
  12625.      {
  12626.          $0 = tolower($0)    # remove case distinctions
  12627.          gsub(/[^a-z0-9_ \t]/, "", $0)  # remove punctuation
  12628.          for (i = 1; i <= NF; i++)
  12629.              freq[$i]++
  12630.      }
  12631.      
  12632.      END {
  12633.          for (word in freq)
  12634.              printf "%s\t%d\n", word, freq[word]
  12635.      }
  12636.  
  12637.    Assuming we have saved this program in a file named `wordfreq.awk',
  12638. and that the data is in `file1', the following pipeline
  12639.  
  12640.      awk -f wordfreq.awk file1 | sort +1 -nr
  12641.  
  12642. produces a table of the words appearing in `file1' in order of
  12643. decreasing frequency.
  12644.  
  12645.    The `awk' program suitably massages the data and produces a word
  12646. frequency table, which is not ordered.
  12647.  
  12648.    The `awk' script's output is then sorted by the `sort' utility and
  12649. printed on the terminal.  The options given to `sort' in this example
  12650. specify to sort using the second field of each input line (skipping one
  12651. field), that the sort keys should be treated as numeric quantities
  12652. (otherwise `15' would come before `5'), and that the sorting should be
  12653. done in descending (reverse) order.
  12654.  
  12655.    We could have even done the `sort' from within the program, by
  12656. changing the `END' action to:
  12657.  
  12658.      END {
  12659.          sort = "sort +1 -nr"
  12660.          for (word in freq)
  12661.              printf "%s\t%d\n", word, freq[word] | sort
  12662.          close(sort)
  12663.      }
  12664.  
  12665.    You would have to use this way of sorting on systems that do not
  12666. have true pipes.
  12667.  
  12668.    See the general operating system documentation for more information
  12669. on how to use the `sort' program.
  12670.  
  12671. 
  12672. File: gawk.info,  Node: History Sorting,  Next: Extract Program,  Prev: Word Sorting,  Up: Miscellaneous Programs
  12673.  
  12674. Removing Duplicates from Unsorted Text
  12675. --------------------------------------
  12676.  
  12677.    The `uniq' program (*note Printing Non-duplicated Lines of Text:
  12678. Uniq Program.), removes duplicate lines from *sorted* data.
  12679.  
  12680.    Suppose, however, you need to remove duplicate lines from a data
  12681. file, but that you wish to preserve the order the lines are in?  A good
  12682. example of this might be a shell history file.  The history file keeps
  12683. a copy of all the commands you have entered, and it is not unusual to
  12684. repeat a command several times in a row.  Occasionally you might wish
  12685. to compact the history by removing duplicate entries.  Yet it is
  12686. desirable to maintain the order of the original commands.
  12687.  
  12688.    This simple program does the job.  It uses two arrays.  The `data'
  12689. array is indexed by the text of each line.  For each line, `data[$0]'
  12690. is incremented.
  12691.  
  12692.    If a particular line has not been seen before, then `data[$0]' will
  12693. be zero.  In that case, the text of the line is stored in
  12694. `lines[count]'.  Each element of `lines' is a unique command, and the
  12695. indices of `lines' indicate the order in which those lines were
  12696. encountered.  The `END' rule simply prints out the lines, in order.
  12697.  
  12698.      # histsort.awk --- compact a shell history file
  12699.      # Arnold Robbins, arnold@gnu.ai.mit.edu, Public Domain
  12700.      # May 1993
  12701.      
  12702.      # Thanks to Byron Rakitzis for the general idea
  12703.      {
  12704.          if (data[$0]++ == 0)
  12705.              lines[++count] = $0
  12706.      }
  12707.      
  12708.      END {
  12709.          for (i = 1; i <= count; i++)
  12710.              print lines[i]
  12711.      }
  12712.  
  12713.    This program also provides a foundation for generating other useful
  12714. information.  For example, using the following `print' satement in the
  12715. `END' rule would indicate how often a particular command was used.
  12716.  
  12717.      print data[lines[i]], lines[i]
  12718.  
  12719.    This works because `data[$0]' was incremented each time a line was
  12720. seen.
  12721.  
  12722. 
  12723. File: gawk.info,  Node: Extract Program,  Next: Simple Sed,  Prev: History Sorting,  Up: Miscellaneous Programs
  12724.  
  12725. Extracting Programs from Texinfo Source Files
  12726. ---------------------------------------------
  12727.  
  12728.    The nodes *Note A Library of `awk' Functions: Library Functions, and
  12729. *Note Practical `awk' Programs: Sample Programs, are the top level
  12730. nodes for a large number of `awk' programs.  If you wish to experiment
  12731. with these programs, it is tedious to have to type them in by hand.
  12732. Here we present a program that can extract parts of a Texinfo input
  12733. file into separate files.
  12734.  
  12735.    This Info file is written in Texinfo, the GNU project's document
  12736. formatting language.  A single Texinfo source file can be used to
  12737. produce both printed and on-line documentation.  The Texinfo language
  12738. is described fully, starting with *Note Introduction: (texi)Top.
  12739.  
  12740.    For our purposes, it is enough to know three things about Texinfo
  12741. input files.
  12742.  
  12743.    * The "at" symbol, `@', is special in Texinfo, much like `\' in C or
  12744.      `awk'.  Literal `@' symbols are represented in Texinfo source
  12745.      files as `@@'.
  12746.  
  12747.    * Comments start with either `@c' or `@comment'.  The file
  12748.      extraction program will work by using special comments that start
  12749.      at the beginning of a line.
  12750.  
  12751.    * Example text that should not be split across a page boundary is
  12752.      bracketed between lines containing `@group' and `@end group'
  12753.      commands.
  12754.  
  12755.    The following program, `extract.awk', reads through a Texinfo source
  12756. file, and does two things, based on the special comments.  Upon seeing
  12757. `@c system ...', it runs a command, by extracting the command text from
  12758. the control line and passing it on to the `system' function (*note
  12759. Built-in Functions for Input/Output: I/O Functions.).  Upon seeing `@c
  12760. file FILENAME', each subsequent line is sent to the file FILENAME,
  12761. until `@c endfile' is encountered.  The rules in `extract.awk' will
  12762. match either `@c' or `@comment' by letting the `omment' part be
  12763. optional.  Lines containing `@group' and `@end group' are simply
  12764. removed.  `extract.awk' uses the `join' library function (*note Merging
  12765. an Array Into a String: Join Function.).
  12766.  
  12767.    The example programs in the on-line Texinfo source for `AWK Language
  12768. Programming' (`gawk.texi') have all been bracketed inside `file', and
  12769. `endfile' lines.  The `gawk' distribution uses a copy of `extract.awk'
  12770. to extract the sample programs and install many of them in a standard
  12771. directory, where `gawk' can find them.
  12772.  
  12773.    `extract.awk' begins by setting `IGNORECASE' to one, so that mixed
  12774. upper-case and lower-case letters in the directives won't matter.
  12775.  
  12776.    The first rule handles calling `system', checking that a command was
  12777. given (`NF' is at least three), and also checking that the command
  12778. exited with a zero exit status, signifying OK.
  12779.  
  12780.      # extract.awk --- extract files and run programs
  12781.      #                 from texinfo files
  12782.      # Arnold Robbins, arnold@gnu.ai.mit.edu, Public Domain
  12783.      # May 1993
  12784.      
  12785.      BEGIN    { IGNORECASE = 1 }
  12786.      
  12787.      /^@c(omment)?[ \t]+system/    \
  12788.      {
  12789.          if (NF < 3) {
  12790.              e = (FILENAME ":" FNR)
  12791.              e = (e  ": badly formed `system' line")
  12792.              print e > "/dev/stderr"
  12793.              next
  12794.          }
  12795.          $1 = ""
  12796.          $2 = ""
  12797.          stat = system($0)
  12798.          if (stat != 0) {
  12799.              e = (FILENAME ":" FNR)
  12800.              e = (e ": warning: system returned " stat)
  12801.              print e > "/dev/stderr"
  12802.          }
  12803.      }
  12804.  
  12805. The variable `e' is used so that the function fits nicely on the screen.
  12806.  
  12807.    The second rule handles moving data into files.  It verifies that a
  12808. file name was given in the directive.  If the file named is not the
  12809. current file, then the current file is closed.  This means that an `@c
  12810. endfile' was not given for that file.  (We should probably print a
  12811. diagnostic in this case, although at the moment we do not.)
  12812.  
  12813.    The `for' loop does the work.  It reads lines using `getline' (*note
  12814. Explicit Input with `getline': Getline.).  For an unexpected end of
  12815. file, it calls the `unexpected_eof' function.  If the line is an
  12816. "endfile" line, then it breaks out of the loop.  If the line is an
  12817. `@group' or `@end group' line, then it ignores it, and goes on to the
  12818. next line.
  12819.  
  12820.    Most of the work is in the following few lines.  If the line has no
  12821. `@' symbols, it can be printed directly.  Otherwise, each leading `@'
  12822. must be stripped off.
  12823.  
  12824.    To remove the `@' symbols, the line is split into separate elements
  12825. of the array `a', using the `split' function (*note Built-in Functions
  12826. for String Manipulation: String Functions.).  Each element of `a' that
  12827. is empty indicates two successive `@' symbols in the original line.
  12828. For each two empty elements (`@@' in the original file), we have to add
  12829. back in a single `@' symbol.
  12830.  
  12831.    When the processing of the array is finished, `join' is called with
  12832. the value of `SUBSEP', to rejoin the pieces back into a single line.
  12833. That line is then printed to the output file.
  12834.  
  12835.      /^@c(omment)?[ \t]+file/    \
  12836.      {
  12837.          if (NF != 3) {
  12838.              e = (FILENAME ":" FNR ": badly formed `file' line")
  12839.              print e > "/dev/stderr"
  12840.              next
  12841.          }
  12842.          if ($3 != curfile) {
  12843.              if (curfile != "")
  12844.                  close(curfile)
  12845.              curfile = $3
  12846.          }
  12847.      
  12848.          for (;;) {
  12849.              if ((getline line) <= 0)
  12850.                  unexpected_eof()
  12851.              if (line ~ /^@c(omment)?[ \t]+endfile/)
  12852.                  break
  12853.              else if (line ~ /^@(end[ \t]+)?group/)
  12854.                  continue
  12855.              if (index(line, "@") == 0) {
  12856.                  print line > curfile
  12857.                  continue
  12858.              }
  12859.              n = split(line, a, "@")
  12860.              # if a[1] == "", means leading @,
  12861.              # don't add one back in.
  12862.              for (i = 2; i <= n; i++) {
  12863.                  if (a[i] == "") { # was an @@
  12864.                      a[i] = "@"
  12865.                      if (a[i+1] == "")
  12866.                          i++
  12867.                  }
  12868.              }
  12869.              print join(a, 1, n, SUBSEP) > curfile
  12870.          }
  12871.      }
  12872.  
  12873.    An important thing to note is the use of the `>' redirection.
  12874. Output done with `>' only opens the file once; it stays open and
  12875. subsequent output is appended to the file (*note Redirecting Output of
  12876. `print' and `printf': Redirection.).  This allows us to easily mix
  12877. program text and explanatory prose for the same sample source file (as
  12878. has been done here!) without any hassle.  The file is only closed when
  12879. a new data file name is encountered, or at the end of the input file.
  12880.  
  12881.    Finally, the function `unexpected_eof' prints an appropriate error
  12882. message and then exits.
  12883.  
  12884.    The `END' rule handles the final cleanup, closing the open file.
  12885.  
  12886.      function unexpected_eof()
  12887.      {
  12888.          printf("%s:%d: unexpected EOF or error\n", \
  12889.              FILENAME, FNR) > "/dev/stderr"
  12890.          exit 1
  12891.      }
  12892.      
  12893.      END {
  12894.          if (curfile)
  12895.              close(curfile)
  12896.      }
  12897.  
  12898. 
  12899. File: gawk.info,  Node: Simple Sed,  Next: Igawk Program,  Prev: Extract Program,  Up: Miscellaneous Programs
  12900.  
  12901. A Simple Stream Editor
  12902. ----------------------
  12903.  
  12904.    The `sed' utility is a "stream editor," a program that reads a
  12905. stream of data, makes changes to it, and passes the modified data on.
  12906. It is often used to make global changes to a large file, or to a stream
  12907. of data generated by a pipeline of commands.
  12908.  
  12909.    While `sed' is a complicated program in its own right, its most
  12910. common use is to perform global substitutions in the middle of a
  12911. pipeline:
  12912.  
  12913.      command1 < orig.data | sed 's/old/new/g' | command2 > result
  12914.  
  12915.    Here, the `s/old/new/g' tells `sed' to look for the regexp `old' on
  12916. each input line, and replace it with the text `new', globally (i.e. all
  12917. the occurrences on a line).  This is similar to `awk''s `gsub' function
  12918. (*note Built-in Functions for String Manipulation: String Functions.).
  12919.  
  12920.    The following program, `awksed.awk', accepts at least two command
  12921. line arguments; the pattern to look for and the text to replace it
  12922. with. Any additional arguments are treated as data file names to
  12923. process. If none are provided, the standard input is used.
  12924.  
  12925.      # awksed.awk --- do s/foo/bar/g using just print
  12926.      #    Thanks to Michael Brennan for the idea
  12927.      
  12928.      # Arnold Robbins, arnold@gnu.ai.mit.edu, Public Domain
  12929.      # August 1995
  12930.      
  12931.      function usage()
  12932.      {
  12933.          print "usage: awksed pat repl [files...]" > "/dev/stderr"
  12934.          exit 1
  12935.      }
  12936.      
  12937.      BEGIN {
  12938.          # validate arguments
  12939.          if (ARGC < 3)
  12940.              usage()
  12941.      
  12942.          RS = ARGV[1]
  12943.          ORS = ARGV[2]
  12944.      
  12945.          # don't use arguments as files
  12946.          ARGV[1] = ARGV[2] = ""
  12947.      }
  12948.      
  12949.      # look ma, no hands!
  12950.      {
  12951.          if (RT == "")
  12952.              printf "%s", $0
  12953.          else
  12954.              print
  12955.      }
  12956.  
  12957.    The program relies on `gawk''s ability to have `RS' be a regexp and
  12958. on the setting of `RT' to the actual text that terminated the record
  12959. (*note How Input is Split into Records: Records.).
  12960.  
  12961.    The idea is to have `RS' be the pattern to look for. `gawk' will
  12962. automatically set `$0' to the text between matches of the pattern.
  12963. This is text that we wish to keep, unmodified.  Then, by setting `ORS'
  12964. to the replacement text, a simple `print' statement will output the
  12965. text we wish to keep, followed by the replacement text.
  12966.  
  12967.    There is one wrinkle to this scheme, which is what to do if the last
  12968. record doesn't end with text that matches `RS'?  Using a `print'
  12969. statement unconditionally prints the replacement text, which is not
  12970. correct.
  12971.  
  12972.    However, if the file did not end in text that matches `RS', `RT'
  12973. will be set to the null string.  In this case, we can print `$0' using
  12974. `printf' (*note Using `printf' Statements for Fancier Printing:
  12975. Printf.).
  12976.  
  12977.    The `BEGIN' rule handles the setup, checking for the right number of
  12978. arguments, and calling `usage' if there is a problem. Then it sets `RS'
  12979. and `ORS' from the command line arguments, and sets `ARGV[1]' and
  12980. `ARGV[2]' to the null string, so that they will not be treated as file
  12981. names (*note Using `ARGC' and `ARGV': ARGC and ARGV.).
  12982.  
  12983.    The `usage' function prints an error message and exits.
  12984.  
  12985.    Finally, the single rule handles the printing scheme outlined above,
  12986. using `print' or `printf' as appropriate, depending upon the value of
  12987. `RT'.
  12988.  
  12989. 
  12990. File: gawk.info,  Node: Igawk Program,  Prev: Simple Sed,  Up: Miscellaneous Programs
  12991.  
  12992. An Easy Way to Use Library Functions
  12993. ------------------------------------
  12994.  
  12995.    Using library functions in `awk' can be very beneficial. It
  12996. encourages code re-use and the writing of general functions. Programs
  12997. are smaller, and therefore clearer.  However, using library functions
  12998. is only easy when writing `awk' programs; it is painful when running
  12999. them, requiring multiple `-f' options.  If `gawk' is unavailable, then
  13000. so too is the `AWKPATH' environment variable and the ability to put
  13001. `awk' functions into a library directory (*note Command Line Options:
  13002. Options.).
  13003.  
  13004.    It would be nice to be able to write programs like so:
  13005.  
  13006.      # library functions
  13007.      @include getopt.awk
  13008.      @include join.awk
  13009.      ...
  13010.      
  13011.      # main program
  13012.      BEGIN {
  13013.          while ((c = getopt(ARGC, ARGV, "a:b:cde")) != -1)
  13014.              ...
  13015.          ...
  13016.      }
  13017.  
  13018.    The following program, `igawk.sh', provides this service.  It
  13019. simulates `gawk''s searching of the `AWKPATH' variable, and also allows
  13020. "nested" includes; i.e. a file that has been included with `@include'
  13021. can contain further `@include' statements.  `igawk' will make an effort
  13022. to only include files once, so that nested includes don't accidentally
  13023. include a library function twice.
  13024.  
  13025.    `igawk' should behave externally just like `gawk'.  This means it
  13026. should accept all of `gawk''s command line arguments, including the
  13027. ability to have multiple source files specified via `-f', and the
  13028. ability to mix command line and library source files.
  13029.  
  13030.    The program is written using the POSIX Shell (`sh') command language.
  13031. The way the program works is as follows:
  13032.  
  13033.   1. Loop through the arguments, saving anything that doesn't represent
  13034.      `awk' source code for later, when the expanded program is run.
  13035.  
  13036.   2. For any arguments that do represent `awk' text, put the arguments
  13037.      into a temporary file that will be expanded.  There are two cases.
  13038.  
  13039.        a. Literal text, provided with `--source' or `--source='.  This
  13040.           text is just echoed directly.  The `echo' program will
  13041.           automatically supply a trailing newline.
  13042.  
  13043.        b. File names provided with `-f'.  We use a neat trick, and echo
  13044.           `@include FILENAME' into the temporary file.  Since the file
  13045.           inclusion program will work the way `gawk' does, this will
  13046.           get the text of the file included into the program at the
  13047.           correct point.
  13048.  
  13049.   3. Run an `awk' program (naturally) over the temporary file to expand
  13050.      `@include' statements.  The expanded program is placed in a second
  13051.      temporary file.
  13052.  
  13053.   4. Run the expanded program with `gawk' and any other original
  13054.      command line arguments that the user supplied (such as the data
  13055.      file names).
  13056.  
  13057.    The initial part of the program turns on shell tracing if the first
  13058. argument was `debug'.  Otherwise, a shell `trap' statement arranges to
  13059. clean up any temporary files on program exit or upon an interrupt.
  13060.  
  13061.    The next part loops through all the command line arguments.  There
  13062. are several cases of interest.
  13063.  
  13064. `--'
  13065.      This ends the arguments to `igawk'.  Anything else should be
  13066.      passed on to the user's `awk' program without being evaluated.
  13067.  
  13068. `-W'
  13069.      This indicates that the next option is specific to `gawk'.  To make
  13070.      argument processing easier, the `-W' is appended to the front of
  13071.      the remaining arguments and the loop continues.  (This is an `sh'
  13072.      programming trick.  Don't worry about it if you are not familiar
  13073.      with `sh'.)
  13074.  
  13075. `-v'
  13076. `-F'
  13077.      These are saved and passed on to `gawk'.
  13078.  
  13079. `-f'
  13080. `--file'
  13081. `--file='
  13082. `-Wfile='
  13083.      The file name is saved to the temporary file `/tmp/ig.s.$$' with an
  13084.      `@include' statement.  The `sed' utility is used to remove the
  13085.      leading option part of the argument (e.g., `--file=').
  13086.  
  13087. `--source'
  13088. `--source='
  13089. `-Wsource='
  13090.      The source text is echoed into `/tmp/ig.s.$$'.
  13091.  
  13092. `--version'
  13093. `--version'
  13094. `-Wversion'
  13095.      `igawk' prints its version number, and runs `gawk --version' to
  13096.      get the `gawk' version information, and then exits.
  13097.  
  13098.    If none of `-f', `--file', `-Wfile', `--source', or `-Wsource', were
  13099. supplied, then the first non-option argument should be the `awk'
  13100. program.  If there are no command line arguments left, `igawk' prints
  13101. an error message and exits.  Otherwise, the first argument is echoed
  13102. into `/tmp/ig.s.$$'.
  13103.  
  13104.    In any case, after the arguments have been processed, `/tmp/ig.s.$$'
  13105. contains the complete text of the original `awk' program.
  13106.  
  13107.    The `$$' in `sh' represents the current process ID number.  It is
  13108. often used in shell programs to generate unique temporary file names.
  13109. This allows multiple users to run `igawk' without worrying that the
  13110. temporary file names will clash.
  13111.  
  13112.    Here's the program:
  13113.  
  13114.      #! /bin/sh
  13115.      
  13116.      # igawk --- like gawk but do @include processing
  13117.      # Arnold Robbins, arnold@gnu.ai.mit.edu, Public Domain
  13118.      # July 1993
  13119.      
  13120.      if [ "$1" = debug ]
  13121.      then
  13122.          set -x
  13123.          shift
  13124.      else
  13125.          # cleanup on exit, hangup, interrupt, quit, termination
  13126.          trap 'rm -f /tmp/ig.[se].$$' 0 1 2 3 15
  13127.      fi
  13128.      
  13129.      while [ $# -ne 0 ] # loop over arguments
  13130.      do
  13131.          case $1 in
  13132.          --)     shift; break;;
  13133.      
  13134.          -W)     shift
  13135.                  set -- -W"$@"
  13136.                  continue;;
  13137.      
  13138.          -[vF])  opts="$opts $1 '$2'"
  13139.                  shift;;
  13140.      
  13141.          -[vF]*) opts="$opts '$1'" ;;
  13142.      
  13143.          -f)     echo @include "$2" >> /tmp/ig.s.$$
  13144.                  shift;;
  13145.      
  13146.          -f*)    f=`echo "$1" | sed 's/-f//'`
  13147.                  echo @include "$f" >> /tmp/ig.s.$$ ;;
  13148.      
  13149.          -?file=*)    # -Wfile or --file
  13150.                  f=`echo "$1" | sed 's/-.file=//'`
  13151.                  echo @include "$f" >> /tmp/ig.s.$$ ;;
  13152.      
  13153.          -?file)    # get arg, $2
  13154.                  echo @include "$2" >> /tmp/ig.s.$$
  13155.                  shift;;
  13156.      
  13157.          -?source=*)    # -Wsource or --source
  13158.                  t=`echo "$1" | sed 's/-.source=//'`
  13159.                  echo "$t" >> /tmp/ig.s.$$ ;;
  13160.      
  13161.          -?source)  # get arg, $2
  13162.                  echo "$2" >> /tmp/ig.s.$$
  13163.                  shift;;
  13164.      
  13165.          -?version)
  13166.                  echo igawk: version 1.0 1>&2
  13167.                  gawk --version
  13168.                  exit 0 ;;
  13169.      
  13170.          -[W-]*)    opts="$opts '$1'" ;;
  13171.      
  13172.          *)      break;;
  13173.          esac
  13174.          shift
  13175.      done
  13176.      
  13177.      if [ ! -s /tmp/ig.s.$$ ]
  13178.      then
  13179.          if [ -z "$1" ]
  13180.          then
  13181.               echo igawk: no program! 1>&2
  13182.               exit 1
  13183.          else
  13184.              echo "$1" > /tmp/ig.s.$$
  13185.              shift
  13186.          fi
  13187.      fi
  13188.      
  13189.      # at this point, /tmp/ig.s.$$ has the program
  13190.  
  13191.    The `awk' program to process `@include' directives reads through the
  13192. program, one line at a time using `getline' (*note Explicit Input with
  13193. `getline': Getline.).  The input file names and `@include' statements
  13194. are managed using a stack.  As each `@include' is encountered, the
  13195. current file name is "pushed" onto the stack, and the file named in the
  13196. `@include' directive becomes the current file name.  As each file is
  13197. finished, the stack is "popped," and the previous input file becomes
  13198. the current input file again.  The process is started by making the
  13199. original file the first one on the stack.
  13200.  
  13201.    The `pathto' function does the work of finding the full path to a
  13202. file.  It simulates `gawk''s behavior when searching the `AWKPATH'
  13203. environment variable (*note The `AWKPATH' Environment Variable: AWKPATH
  13204. Variable.).  If a file name has a `/' in it, no path search is done.
  13205. Otherwise, the file name is concatenated with the name of each
  13206. directory in the path, and an attempt is made to open the generated file
  13207. name.  The only way in `awk' to test if a file can be read is to go
  13208. ahead and try to read it with `getline'; that is what `pathto' does.
  13209. If the file can be read, it is closed, and the file name is returned.
  13210.  
  13211.      gawk -- '
  13212.      # process @include directives
  13213.      
  13214.      function pathto(file,    i, t, junk)
  13215.      {
  13216.          if (index(file, "/") != 0)
  13217.              return file
  13218.      
  13219.          for (i = 1; i <= ndirs; i++) {
  13220.              t = (pathlist[i] "/" file)
  13221.              if ((getline junk < t) > 0) {
  13222.                  # found it
  13223.                  close(t)
  13224.                  return t
  13225.              }
  13226.          }
  13227.          return ""
  13228.      }
  13229.  
  13230.    The main program is contained inside one `BEGIN' rule.  The first
  13231. thing it does is set up the `pathlist' array that `pathto' uses.  After
  13232. splitting the path on `:', null elements are replaced with `"."', which
  13233. represents the current directory.
  13234.  
  13235.      BEGIN {
  13236.          path = ENVIRON["AWKPATH"]
  13237.          ndirs = split(path, pathlist, ":")
  13238.          for (i = 1; i <= ndirs; i++) {
  13239.              if (pathlist[i] == "")
  13240.                  pathlist[i] = "."
  13241.          }
  13242.  
  13243.    The stack is initialized with `ARGV[1]', which will be
  13244. `/tmp/ig.s.$$'.  The main loop comes next.  Input lines are read in
  13245. succession. Lines that do not start with `@include' are printed
  13246. verbatim.
  13247.  
  13248.    If the line does start with `@include', the file name is in `$2'.
  13249. `pathto' is called to generate the full path.  If it could not, then we
  13250. print an error message and continue.
  13251.  
  13252.    The next thing to check is if the file has been included already.
  13253. The `processed' array is indexed by the full file name of each included
  13254. file, and it tracks this information for us.  If the file has been
  13255. seen, a warning message is printed. Otherwise, the new file name is
  13256. pushed onto the stack and processing continues.
  13257.  
  13258.    Finally, when `getline' encounters the end of the input file, the
  13259. file is closed and the stack is popped.  When `stackptr' is less than
  13260. zero, the program is done.
  13261.  
  13262.          stackptr = 0
  13263.          input[stackptr] = ARGV[1] # ARGV[1] is first file
  13264.      
  13265.          for (; stackptr >= 0; stackptr--) {
  13266.              while ((getline < input[stackptr]) > 0) {
  13267.                  if (tolower($1) != "@include") {
  13268.                      print
  13269.                      continue
  13270.                  }
  13271.                  fpath = pathto($2)
  13272.                  if (fpath == "") {
  13273.                      printf("igawk:%s:%d: cannot find %s\n", \
  13274.                          input[stackptr], FNR, $2) > "/dev/stderr"
  13275.                      continue
  13276.                  }
  13277.                  if (! (fpath in processed)) {
  13278.                      processed[fpath] = input[stackptr]
  13279.                      input[++stackptr] = fpath
  13280.                  } else
  13281.                      print $2, "included in", input[stackptr], \
  13282.                          "already included in", \
  13283.                          processed[fpath] > "/dev/stderr"
  13284.              }
  13285.              close(input[stackptr])
  13286.          }
  13287.      }' /tmp/ig.s.$$ > /tmp/ig.e.$$
  13288.  
  13289.    The last step is to call `gawk' with the expanded program and the
  13290. original options and command line arguments that the user supplied.
  13291. `gawk''s exit status is passed back on to `igawk''s calling program.
  13292.  
  13293.      eval gawk -f /tmp/ig.e.$$ $opts -- "$@"
  13294.      
  13295.      exit $?
  13296.  
  13297.    This version of `igawk' represents my third attempt at this program.
  13298. There are three key simplifications that made the program work better.
  13299.  
  13300.   1. Using `@include' even for the files named with `-f' makes building
  13301.      the initial collected `awk' program much simpler; all the
  13302.      `@include' processing can be done once.
  13303.  
  13304.   2. The `pathto' function doesn't try to save the line read with
  13305.      `getline' when testing for the file's accessibility.  Trying to
  13306.      save this line for use with the main program complicates things
  13307.      considerably.
  13308.  
  13309.   3. Using a `getline' loop in the `BEGIN' rule does it all in one
  13310.      place.  It is not necessary to call out to a separate loop for
  13311.      processing nested `@include' statements.
  13312.  
  13313.    Also, this program illustrates that it is often worthwhile to combine
  13314. `sh' and `awk' programming together.  You can usually accomplish quite
  13315. a lot, without having to resort to low-level programming in C or C++,
  13316. and it is frequently easier to do certain kinds of string and argument
  13317. manipulation using the shell than it is in `awk'.
  13318.  
  13319.    Finally, `igawk' shows that it is not always necessary to add new
  13320. features to a program; they can often be layered on top.  With `igawk',
  13321. there is no real reason to build `@include' processing into `gawk'
  13322. itself.
  13323.  
  13324.    As an additional example of this, consider the idea of having two
  13325. files in a directory in the search path.
  13326.  
  13327. `default.awk'
  13328.      This file would contain a set of default library functions, such
  13329.      as `getopt' and `assert'.
  13330.  
  13331. `site.awk'
  13332.      This file would contain library functions that are specific to a
  13333.      site or installation, i.e. locally developed functions.  Having a
  13334.      separate file allows `default.awk' to change with new `gawk'
  13335.      releases, without requiring the system administrator to update it
  13336.      each time by adding the local functions.
  13337.  
  13338.    One user suggested that `gawk' be modified to automatically read
  13339. these files upon startup.  Instead, it would be very simple to modify
  13340. `igawk' to do this. Since `igawk' can process nested `@include'
  13341. directives, `default.awk' could simply contain `@include' statements
  13342. for the desired library functions.
  13343.  
  13344. 
  13345. File: gawk.info,  Node: Language History,  Next: Gawk Summary,  Prev: Sample Programs,  Up: Top
  13346.  
  13347. The Evolution of the `awk' Language
  13348. ***********************************
  13349.  
  13350.    This Info file describes the GNU implementation of `awk', which
  13351. follows the POSIX specification.  Many `awk' users are only familiar
  13352. with the original `awk' implementation in Version 7 Unix.  (This
  13353. implementation was the basis for `awk' in Berkeley Unix, through
  13354. 4.3-Reno.  The 4.4 release of Berkeley Unix uses `gawk' 2.15.2 for its
  13355. version of `awk'.) This chapter briefly describes the evolution of the
  13356. `awk' language, with cross references to other parts of the Info file
  13357. where you can find more information.
  13358.  
  13359. * Menu:
  13360.  
  13361. * V7/SVR3.1::                   The major changes between V7 and System V
  13362.                                 Release 3.1.
  13363. * SVR4::                        Minor changes between System V Releases 3.1
  13364.                                 and 4.
  13365. * POSIX::                       New features from the POSIX standard.
  13366. * BTL::                         New features from the AT&T Bell Laboratories
  13367.                                 version of `awk'.
  13368. * POSIX/GNU::                   The extensions in `gawk' not in POSIX
  13369.                                 `awk'.
  13370.  
  13371. 
  13372. File: gawk.info,  Node: V7/SVR3.1,  Next: SVR4,  Prev: Language History,  Up: Language History
  13373.  
  13374. Major Changes between V7 and SVR3.1
  13375. ===================================
  13376.  
  13377.    The `awk' language evolved considerably between the release of
  13378. Version 7 Unix (1978) and the new version first made generally
  13379. available in System V Release 3.1 (1987).  This section summarizes the
  13380. changes, with cross-references to further details.
  13381.  
  13382.    * The requirement for `;' to separate rules on a line (*note `awk'
  13383.      Statements Versus Lines: Statements/Lines.).
  13384.  
  13385.    * User-defined functions, and the `return' statement (*note
  13386.      User-defined Functions: User-defined.).
  13387.  
  13388.    * The `delete' statement (*note The `delete' Statement: Delete.).
  13389.  
  13390.    * The `do'-`while' statement (*note The `do'-`while' Statement: Do
  13391.      Statement.).
  13392.  
  13393.    * The built-in functions `atan2', `cos', `sin', `rand' and `srand'
  13394.      (*note Numeric Built-in Functions: Numeric Functions.).
  13395.  
  13396.    * The built-in functions `gsub', `sub', and `match' (*note Built-in
  13397.      Functions for String Manipulation: String Functions.).
  13398.  
  13399.    * The built-in functions `close', and `system' (*note Built-in
  13400.      Functions for Input/Output: I/O Functions.).
  13401.  
  13402.    * The `ARGC', `ARGV', `FNR', `RLENGTH', `RSTART', and `SUBSEP'
  13403.      built-in variables (*note Built-in Variables::.).
  13404.  
  13405.    * The conditional expression using the ternary operator `?:' (*note
  13406.      Conditional Expressions: Conditional Exp.).
  13407.  
  13408.    * The exponentiation operator `^' (*note Arithmetic Operators:
  13409.      Arithmetic Ops.) and its assignment operator form `^=' (*note
  13410.      Assignment Expressions: Assignment Ops.).
  13411.  
  13412.    * C-compatible operator precedence, which breaks some old `awk'
  13413.      programs (*note Operator Precedence (How Operators Nest):
  13414.      Precedence.).
  13415.  
  13416.    * Regexps as the value of `FS' (*note Specifying How Fields are
  13417.      Separated: Field Separators.), and as the third argument to the
  13418.      `split' function (*note Built-in Functions for String
  13419.      Manipulation: String Functions.).
  13420.  
  13421.    * Dynamic regexps as operands of the `~' and `!~' operators (*note
  13422.      How to Use Regular Expressions: Regexp Usage.).
  13423.  
  13424.    * The escape sequences `\b', `\f', and `\r' (*note Escape
  13425.      Sequences::.).  (Some vendors have updated their old versions of
  13426.      `awk' to recognize `\r', `\b', and `\f', but this is not something
  13427.      you can rely on.)
  13428.  
  13429.    * Redirection of input for the `getline' function (*note Explicit
  13430.      Input with `getline': Getline.).
  13431.  
  13432.    * Multiple `BEGIN' and `END' rules (*note The `BEGIN' and `END'
  13433.      Special Patterns: BEGIN/END.).
  13434.  
  13435.    * Multi-dimensional arrays (*note Multi-dimensional Arrays:
  13436.      Multi-dimensional.).
  13437.  
  13438. 
  13439. File: gawk.info,  Node: SVR4,  Next: POSIX,  Prev: V7/SVR3.1,  Up: Language History
  13440.  
  13441. Changes between SVR3.1 and SVR4
  13442. ===============================
  13443.  
  13444.    The System V Release 4 version of Unix `awk' added these features
  13445. (some of which originated in `gawk'):
  13446.  
  13447.    * The `ENVIRON' variable (*note Built-in Variables::.).
  13448.  
  13449.    * Multiple `-f' options on the command line (*note Command Line
  13450.      Options: Options.).
  13451.  
  13452.    * The `-v' option for assigning variables before program execution
  13453.      begins (*note Command Line Options: Options.).
  13454.  
  13455.    * The `--' option for terminating command line options.
  13456.  
  13457.    * The `\a', `\v', and `\x' escape sequences (*note Escape
  13458.      Sequences::.).
  13459.  
  13460.    * A defined return value for the `srand' built-in function (*note
  13461.      Numeric Built-in Functions: Numeric Functions.).
  13462.  
  13463.    * The `toupper' and `tolower' built-in string functions for case
  13464.      translation (*note Built-in Functions for String Manipulation:
  13465.      String Functions.).
  13466.  
  13467.    * A cleaner specification for the `%c' format-control letter in the
  13468.      `printf' function (*note Format-Control Letters: Control Letters.).
  13469.  
  13470.    * The ability to dynamically pass the field width and precision
  13471.      (`"%*.*d"') in the argument list of the `printf' function (*note
  13472.      Format-Control Letters: Control Letters.).
  13473.  
  13474.    * The use of regexp constants such as `/foo/' as expressions, where
  13475.      they are equivalent to using the matching operator, as in `$0 ~
  13476.      /foo/' (*note Using Regular Expression Constants: Using Constant
  13477.      Regexps.).
  13478.  
  13479. 
  13480. File: gawk.info,  Node: POSIX,  Next: BTL,  Prev: SVR4,  Up: Language History
  13481.  
  13482. Changes between SVR4 and POSIX `awk'
  13483. ====================================
  13484.  
  13485.    The POSIX Command Language and Utilities standard for `awk'
  13486. introduced the following changes into the language:
  13487.  
  13488.    * The use of `-W' for implementation-specific options.
  13489.  
  13490.    * The use of `CONVFMT' for controlling the conversion of numbers to
  13491.      strings (*note Conversion of Strings and Numbers: Conversion.).
  13492.  
  13493.    * The concept of a numeric string, and tighter comparison rules to go
  13494.      with it (*note Variable Typing and Comparison Expressions: Typing
  13495.      and Comparison.).
  13496.  
  13497.    * More complete documentation of many of the previously undocumented
  13498.      features of the language.
  13499.  
  13500.    The following common extensions are not permitted by the POSIX
  13501. standard:
  13502.  
  13503.    * `\x' escape sequences are not recognized (*note Escape
  13504.      Sequences::.).
  13505.  
  13506.    * The synonym `func' for the keyword `function' is not recognized
  13507.      (*note Function Definition Syntax: Definition Syntax.).
  13508.  
  13509.    * The operators `**' and `**=' cannot be used in place of `^' and
  13510.      `^=' (*note Arithmetic Operators: Arithmetic Ops., and also *note
  13511.      Assignment Expressions: Assignment Ops.).
  13512.  
  13513.    * Specifying `-Ft' on the command line does not set the value of
  13514.      `FS' to be a single tab character (*note Specifying How Fields are
  13515.      Separated: Field Separators.).
  13516.  
  13517.    * The `fflush' built-in function is not supported (*note Built-in
  13518.      Functions for Input/Output: I/O Functions.).
  13519.  
  13520. 
  13521. File: gawk.info,  Node: BTL,  Next: POSIX/GNU,  Prev: POSIX,  Up: Language History
  13522.  
  13523. Extensions in the AT&T Bell Laboratories `awk'
  13524. ==============================================
  13525.  
  13526.    Brian Kernighan, one of the original designers of Unix `awk', has
  13527. made his version available via anonymous `ftp' (*note Other Freely
  13528. Available `awk' Implementations: Other Versions.).  This section
  13529. describes extensions in his version of `awk' that are not in POSIX
  13530. `awk'.
  13531.  
  13532.    * The `-mf=NNN' and `-mr=NNN' command line options to set the
  13533.      maximum number of fields, and the maximum record size, respectively
  13534.      (*note Command Line Options: Options.).
  13535.  
  13536.    * The `fflush' built-in function for flushing buffered output (*note
  13537.      Built-in Functions for Input/Output: I/O Functions.).
  13538.  
  13539. 
  13540. File: gawk.info,  Node: POSIX/GNU,  Prev: BTL,  Up: Language History
  13541.  
  13542. Extensions in `gawk' Not in POSIX `awk'
  13543. =======================================
  13544.  
  13545.    The GNU implementation, `gawk', adds a number of features.  This
  13546. sections lists them in the order they were added to `gawk'.  They can
  13547. all be disabled with either the `--traditional' or `--posix' options
  13548. (*note Command Line Options: Options.).
  13549.  
  13550.    Version 2.10 of `gawk' introduced these features:
  13551.  
  13552.    * The `AWKPATH' environment variable for specifying a path search for
  13553.      the `-f' command line option (*note Command Line Options:
  13554.      Options.).
  13555.  
  13556.    * The `IGNORECASE' variable and its effects (*note Case-sensitivity
  13557.      in Matching: Case-sensitivity.).
  13558.  
  13559.    * The `/dev/stdin', `/dev/stdout', `/dev/stderr', and `/dev/fd/N'
  13560.      file name interpretation (*note Special File Names in `gawk':
  13561.      Special Files.).
  13562.  
  13563.    Version 2.13 of `gawk' introduced these features:
  13564.  
  13565.    * The `FIELDWIDTHS' variable and its effects (*note Reading
  13566.      Fixed-width Data: Constant Size.).
  13567.  
  13568.    * The `systime' and `strftime' built-in functions for obtaining and
  13569.      printing time stamps (*note Functions for Dealing with Time
  13570.      Stamps: Time Functions.).
  13571.  
  13572.    * The `-W lint' option to provide source code and run time error and
  13573.      portability checking (*note Command Line Options: Options.).
  13574.  
  13575.    * The `-W compat' option to turn off these extensions (*note Command
  13576.      Line Options: Options.).
  13577.  
  13578.    * The `-W posix' option for full POSIX compliance (*note Command
  13579.      Line Options: Options.).
  13580.  
  13581.    Version 2.14 of `gawk' introduced these features:
  13582.  
  13583.    * The `next file' statement for skipping to the next data file
  13584.      (*note The `nextfile' Statement: Nextfile Statement.).
  13585.  
  13586.    Version 2.15 of `gawk' introduced these features:
  13587.  
  13588.    * The `ARGIND' variable, that tracks the movement of `FILENAME'
  13589.      through `ARGV'  (*note Built-in Variables::.).
  13590.  
  13591.    * The `ERRNO' variable, that contains the system error message when
  13592.      `getline' returns -1, or when `close' fails (*note Built-in
  13593.      Variables::.).
  13594.  
  13595.    * The ability to use GNU-style long named options that start with
  13596.      `--' (*note Command Line Options: Options.).
  13597.  
  13598.    * The `--source' option for mixing command line and library file
  13599.      source code (*note Command Line Options: Options.).
  13600.  
  13601.    * The `/dev/pid', `/dev/ppid', `/dev/pgrpid', and `/dev/user' file
  13602.      name interpretation (*note Special File Names in `gawk': Special
  13603.      Files.).
  13604.  
  13605.    Version 3.0 of `gawk' introduced these features:
  13606.  
  13607.    * The `next file' statement became `nextfile' (*note The `nextfile'
  13608.      Statement: Nextfile Statement.).
  13609.  
  13610.    * The `--lint-old' option to warn about constructs that are not
  13611.      available in the original Version 7 Unix version of `awk' (*note
  13612.      Major Changes between V7 and SVR3.1: V7/SVR3.1.).
  13613.  
  13614.    * The `--traditional' option was added as a better name for
  13615.      `--compat' (*note Command Line Options: Options.).
  13616.  
  13617.    * The ability for `FS' to be a null string, and for the third
  13618.      argument to `split' to be the null string (*note Making Each
  13619.      Character a Separate Field: Single Character Fields.).
  13620.  
  13621.    * The ability for `RS' to be a regexp (*note How Input is Split into
  13622.      Records: Records.).
  13623.  
  13624.    * The `RT' variable (*note How Input is Split into Records:
  13625.      Records.).
  13626.  
  13627.    * The `gensub' function for more powerful text manipulation (*note
  13628.      Built-in Functions for String Manipulation: String Functions.).
  13629.  
  13630.    * The `strftime' function acquired a default time format, allowing
  13631.      it to be called with no arguments (*note Functions for Dealing
  13632.      with Time Stamps: Time Functions.).
  13633.  
  13634.    * Full support for both POSIX and GNU regexps (*note Regular
  13635.      Expressions: Regexp.).
  13636.  
  13637.    * The `--re-interval' option to provide interval expressions in
  13638.      regexps (*note Regular Expression Operators: Regexp Operators.).
  13639.  
  13640.    * `IGNORECASE' changed, now applying to string comparison as well as
  13641.      regexp operations (*note Case-sensitivity in Matching:
  13642.      Case-sensitivity.).
  13643.  
  13644.    * The `-m' option and the `fflush' function from the Bell Labs
  13645.      research version of `awk' (*note Command Line Options: Options.;
  13646.      also *note Built-in Functions for Input/Output: I/O Functions.).
  13647.  
  13648.    * The use of GNU Autoconf to control the configuration process
  13649.      (*note Compiling `gawk' for Unix: Quick Installation.).
  13650.  
  13651.    * Amiga support (*note Installing `gawk' on an Amiga: Amiga
  13652.      Installation.).
  13653.  
  13654. 
  13655. File: gawk.info,  Node: Gawk Summary,  Next: Installation,  Prev: Language History,  Up: Top
  13656.  
  13657. `gawk' Summary
  13658. **************
  13659.  
  13660.    This appendix provides a brief summary of the `gawk' command line
  13661. and the `awk' language.  It is designed to serve as "quick reference."
  13662. It is therefore terse, but complete.
  13663.  
  13664. * Menu:
  13665.  
  13666. * Command Line Summary::        Recapitulation of the command line.
  13667. * Language Summary::            A terse review of the language.
  13668. * Variables/Fields::            Variables, fields, and arrays.
  13669. * Rules Summary::               Patterns and Actions, and their component
  13670.                                 parts.
  13671. * Actions Summary::             Quick overview of actions.
  13672. * Functions Summary::           Defining and calling functions.
  13673. * Historical Features::         Some undocumented but supported "features".
  13674.  
  13675. 
  13676. File: gawk.info,  Node: Command Line Summary,  Next: Language Summary,  Prev: Gawk Summary,  Up: Gawk Summary
  13677.  
  13678. Command Line Options Summary
  13679. ============================
  13680.  
  13681.    The command line consists of options to `gawk' itself, the `awk'
  13682. program text (if not supplied via the `-f' option), and values to be
  13683. made available in the `ARGC' and `ARGV' predefined `awk' variables:
  13684.  
  13685.      gawk [POSIX OR GNU STYLE OPTIONS] -f SOURCE-FILE [`--'] FILE ...
  13686.      gawk [POSIX OR GNU STYLE OPTIONS] [`--'] 'PROGRAM' FILE ...
  13687.  
  13688.    The options that `gawk' accepts are:
  13689.  
  13690. `-F FS'
  13691. `--field-separator FS'
  13692.      Use FS for the input field separator (the value of the `FS'
  13693.      predefined variable).
  13694.  
  13695. `-f PROGRAM-FILE'
  13696. `--file PROGRAM-FILE'
  13697.      Read the `awk' program source from the file PROGRAM-FILE, instead
  13698.      of from the first command line argument.
  13699.  
  13700. `-mf=NNN'
  13701. `-mr=NNN'
  13702.      The `f' flag sets the maximum number of fields, and the `r' flag
  13703.      sets the maximum record size.  These options are ignored by
  13704.      `gawk', since `gawk' has no predefined limits; they are only for
  13705.      compatibility with the Bell Labs research version of Unix `awk'.
  13706.  
  13707. `-v VAR=VAL'
  13708. `--assign VAR=VAL'
  13709.      Assign the variable VAR the value VAL before program execution
  13710.      begins.
  13711.  
  13712. `-W traditional'
  13713. `-W compat'
  13714. `--traditional'
  13715. `--compat'
  13716.      Use compatibility mode, in which `gawk' extensions are turned off.
  13717.  
  13718. `-W copyleft'
  13719. `-W copyright'
  13720. `--copyleft'
  13721. `--copyright'
  13722.      Print the short version of the General Public License on the error
  13723.      output.  This option may disappear in a future version of `gawk'.
  13724.  
  13725. `-W help'
  13726. `-W usage'
  13727. `--help'
  13728. `--usage'
  13729.      Print a relatively short summary of the available options on the
  13730.      error output.
  13731.  
  13732. `-W lint'
  13733. `--lint'
  13734.      Give warnings about dubious or non-portable `awk' constructs.
  13735.  
  13736. `-W lint-old'
  13737. `--lint-old'
  13738.      Warn about constructs that are not available in the original
  13739.      Version 7 Unix version of `awk'.
  13740.  
  13741. `-W posix'
  13742. `--posix'
  13743.      Use POSIX compatibility mode, in which `gawk' extensions are
  13744.      turned off and additional restrictions apply.
  13745.  
  13746. `-W re-interval'
  13747. `--re-interval'
  13748.      Allow interval expressions (*note Regular Expression Operators:
  13749.      Regexp Operators.), in regexps.
  13750.  
  13751. `-W source=PROGRAM-TEXT'
  13752. `--source PROGRAM-TEXT'
  13753.      Use PROGRAM-TEXT as `awk' program source code.  This option allows
  13754.      mixing command line source code with source code from files, and is
  13755.      particularly useful for mixing command line programs with library
  13756.      functions.
  13757.  
  13758. `-W version'
  13759. `--version'
  13760.      Print version information for this particular copy of `gawk' on
  13761.      the error output.
  13762.  
  13763. `--'
  13764.      Signal the end of options.  This is useful to allow further
  13765.      arguments to the `awk' program itself to start with a `-'.  This
  13766.      is mainly for consistency with POSIX argument parsing conventions.
  13767.  
  13768.    Any other options are flagged as invalid, but are otherwise ignored.
  13769. *Note Command Line Options: Options, for more details.
  13770.  
  13771. 
  13772. File: gawk.info,  Node: Language Summary,  Next: Variables/Fields,  Prev: Command Line Summary,  Up: Gawk Summary
  13773.  
  13774. Language Summary
  13775. ================
  13776.  
  13777.    An `awk' program consists of a sequence of zero or more
  13778. pattern-action statements and optional function definitions.  One or
  13779. the other of the pattern and action may be omitted.
  13780.  
  13781.      PATTERN    { ACTION STATEMENTS }
  13782.      PATTERN
  13783.                { ACTION STATEMENTS }
  13784.      
  13785.      function NAME(PARAMETER LIST)     { ACTION STATEMENTS }
  13786.  
  13787.    `gawk' first reads the program source from the PROGRAM-FILE(s), if
  13788. specified, or from the first non-option argument on the command line.
  13789. The `-f' option may be used multiple times on the command line.  `gawk'
  13790. reads the program text from all the PROGRAM-FILE files, effectively
  13791. concatenating them in the order they are specified.  This is useful for
  13792. building libraries of `awk' functions, without having to include them
  13793. in each new `awk' program that uses them.  To use a library function in
  13794. a file from a program typed in on the command line, specify `--source
  13795. 'PROGRAM'', and type your program in between the single quotes.  *Note
  13796. Command Line Options: Options.
  13797.  
  13798.    The environment variable `AWKPATH' specifies a search path to use
  13799. when finding source files named with the `-f' option.  The default
  13800. path, which is `.:/usr/local/share/awk'(1) is used if `AWKPATH' is not
  13801. set.  If a file name given to the `-f' option contains a `/' character,
  13802. no path search is performed.  *Note The `AWKPATH' Environment Variable:
  13803. AWKPATH Variable.
  13804.  
  13805.    `gawk' compiles the program into an internal form, and then proceeds
  13806. to read each file named in the `ARGV' array.  The initial values of
  13807. `ARGV' come from the command line arguments.  If there are no files
  13808. named on the command line, `gawk' reads the standard input.
  13809.  
  13810.    If a "file" named on the command line has the form `VAR=VAL', it is
  13811. treated as a variable assignment: the variable VAR is assigned the
  13812. value VAL.  If any of the files have a value that is the null string,
  13813. that element in the list is skipped.
  13814.  
  13815.    For each record in the input, `gawk' tests to see if it matches any
  13816. PATTERN in the `awk' program.  For each pattern that the record
  13817. matches, the associated ACTION is executed.
  13818.  
  13819.    ---------- Footnotes ----------
  13820.  
  13821.    (1)  The path may use a directory other than `/usr/local/share/awk',
  13822. depending upon how `gawk' was built and installed.
  13823.  
  13824. 
  13825. File: gawk.info,  Node: Variables/Fields,  Next: Rules Summary,  Prev: Language Summary,  Up: Gawk Summary
  13826.  
  13827. Variables and Fields
  13828. ====================
  13829.  
  13830.    `awk' variables are not declared; they come into existence when they
  13831. are first used.  Their values are either floating-point numbers or
  13832. strings.  `awk' also has one-dimensional arrays; multiple-dimensional
  13833. arrays may be simulated.  There are several predefined variables that
  13834. `awk' sets as a program runs; these are summarized below.
  13835.  
  13836. * Menu:
  13837.  
  13838. * Fields Summary::              Input field splitting.
  13839. * Built-in Summary::            `awk''s built-in variables.
  13840. * Arrays Summary::              Using arrays.
  13841. * Data Type Summary::           Values in `awk' are numbers or strings.
  13842.  
  13843. 
  13844. File: gawk.info,  Node: Fields Summary,  Next: Built-in Summary,  Prev: Variables/Fields,  Up: Variables/Fields
  13845.  
  13846. Fields
  13847. ------
  13848.  
  13849.    As each input line is read, `gawk' splits the line into FIELDS,
  13850. using the value of the `FS' variable as the field separator.  If `FS'
  13851. is a single character, fields are separated by that character.
  13852. Otherwise, `FS' is expected to be a full regular expression.  In the
  13853. special case that `FS' is a single space, fields are separated by runs
  13854. of spaces and/or tabs.  If `FS' is the null string (`""'), then each
  13855. individual character in the record becomes a separate field.  Note that
  13856. the value of `IGNORECASE' (*note Case-sensitivity in Matching:
  13857. Case-sensitivity.) also affects how fields are split when `FS' is a
  13858. regular expression.
  13859.  
  13860.    Each field in the input line may be referenced by its position, `$1',
  13861. `$2', and so on.  `$0' is the whole line.  The value of a field may be
  13862. assigned to as well.  Field numbers need not be constants:
  13863.  
  13864.      n = 5
  13865.      print $n
  13866.  
  13867. prints the fifth field in the input line.  The variable `NF' is set to
  13868. the total number of fields in the input line.
  13869.  
  13870.    References to non-existent fields (i.e. fields after `$NF') return
  13871. the null string.  However, assigning to a non-existent field (e.g.,
  13872. `$(NF+2) = 5') increases the value of `NF', creates any intervening
  13873. fields with the null string as their value, and causes the value of
  13874. `$0' to be recomputed, with the fields being separated by the value of
  13875. `OFS'.  *Note Reading Input Files: Reading Files.
  13876.  
  13877. 
  13878. File: gawk.info,  Node: Built-in Summary,  Next: Arrays Summary,  Prev: Fields Summary,  Up: Variables/Fields
  13879.  
  13880. Built-in Variables
  13881. ------------------
  13882.  
  13883.    `gawk''s built-in variables are:
  13884.  
  13885. `ARGC'
  13886.      The number of elements in `ARGV'. See below for what is actually
  13887.      included in `ARGV'.
  13888.  
  13889. `ARGIND'
  13890.      The index in `ARGV' of the current file being processed.  When
  13891.      `gawk' is processing the input data files, it is always true that
  13892.      `FILENAME == ARGV[ARGIND]'.
  13893.  
  13894. `ARGV'
  13895.      The array of command line arguments.  The array is indexed from
  13896.      zero to `ARGC' - 1.  Dynamically changing `ARGC' and the contents
  13897.      of `ARGV' can control the files used for data.  A null-valued
  13898.      element in `ARGV' is ignored. `ARGV' does not include the options
  13899.      to `awk' or the text of the `awk' program itself.
  13900.  
  13901. `CONVFMT'
  13902.      The conversion format to use when converting numbers to strings.
  13903.  
  13904. `FIELDWIDTHS'
  13905.      A space separated list of numbers describing the fixed-width input
  13906.      data.
  13907.  
  13908. `ENVIRON'
  13909.      An array of environment variable values.  The array is indexed by
  13910.      variable name, each element being the value of that variable.
  13911.      Thus, the environment variable `HOME' is `ENVIRON["HOME"]'.  One
  13912.      possible value might be `/home/arnold'.
  13913.  
  13914.      Changing this array does not affect the environment seen by
  13915.      programs which `gawk' spawns via redirection or the `system'
  13916.      function.  (This may change in a future version of `gawk'.)
  13917.  
  13918.      Some operating systems do not have environment variables.  The
  13919.      `ENVIRON' array is empty when running on these systems.
  13920.  
  13921. `ERRNO'
  13922.      The system error message when an error occurs using `getline' or
  13923.      `close'.
  13924.  
  13925. `FILENAME'
  13926.      The name of the current input file.  If no files are specified on
  13927.      the command line, the value of `FILENAME' is the null string.
  13928.  
  13929. `FNR'
  13930.      The input record number in the current input file.
  13931.  
  13932. `FS'
  13933.      The input field separator, a space by default.
  13934.  
  13935. `IGNORECASE'
  13936.      The case-sensitivity flag for string comparisons and regular
  13937.      expression operations.  If `IGNORECASE' has a non-zero value, then
  13938.      pattern matching in rules, record separating with `RS', field
  13939.      splitting with `FS', regular expression matching with `~' and
  13940.      `!~', and the `gensub', `gsub', `index', `match', `split' and
  13941.      `sub' built-in functions all ignore case when doing regular
  13942.      expression operations, and all string comparisons are done
  13943.      ignoring case.
  13944.  
  13945. `NF'
  13946.      The number of fields in the current input record.
  13947.  
  13948. `NR'
  13949.      The total number of input records seen so far.
  13950.  
  13951. `OFMT'
  13952.      The output format for numbers for the `print' statement, `"%.6g"'
  13953.      by default.
  13954.  
  13955. `OFS'
  13956.      The output field separator, a space by default.
  13957.  
  13958. `ORS'
  13959.      The output record separator, by default a newline.
  13960.  
  13961. `RS'
  13962.      The input record separator, by default a newline.  If `RS' is set
  13963.      to the null string, then records are separated by blank lines.
  13964.      When `RS' is set to the null string, then the newline character
  13965.      always acts as a field separator, in addition to whatever value
  13966.      `FS' may have.  If `RS' is set to a multi-character string, it
  13967.      denotes a regexp; input text matching the regexp separates records.
  13968.  
  13969. `RT'
  13970.      The input text that matched the text denoted by `RS', the record
  13971.      separator.
  13972.  
  13973. `RSTART'
  13974.      The index of the first character last matched by `match'; zero if
  13975.      no match.
  13976.  
  13977. `RLENGTH'
  13978.      The length of the string last matched by `match'; -1 if no match.
  13979.  
  13980. `SUBSEP'
  13981.      The string used to separate multiple subscripts in array elements,
  13982.      by default `"\034"'.
  13983.  
  13984.    *Note Built-in Variables::, for more information.
  13985.  
  13986. 
  13987. File: gawk.info,  Node: Arrays Summary,  Next: Data Type Summary,  Prev: Built-in Summary,  Up: Variables/Fields
  13988.  
  13989. Arrays
  13990. ------
  13991.  
  13992.    Arrays are subscripted with an expression between square brackets
  13993. (`[' and `]').  Array subscripts are *always* strings; numbers are
  13994. converted to strings as necessary, following the standard conversion
  13995. rules (*note Conversion of Strings and Numbers: Conversion.).
  13996.  
  13997.    If you use multiple expressions separated by commas inside the square
  13998. brackets, then the array subscript is a string consisting of the
  13999. concatenation of the individual subscript values, converted to strings,
  14000. separated by the subscript separator (the value of `SUBSEP').
  14001.  
  14002.    The special operator `in' may be used in a conditional context to
  14003. see if an array has an index consisting of a particular value.
  14004.  
  14005.      if (val in array)
  14006.              print array[val]
  14007.  
  14008.    If the array has multiple subscripts, use `(i, j, ...) in ARRAY' to
  14009. test for existence of an element.
  14010.  
  14011.    The `in' construct may also be used in a `for' loop to iterate over
  14012. all the elements of an array.  *Note Scanning All Elements of an Array:
  14013. Scanning an Array.
  14014.  
  14015.    You can remove an element from an array using the `delete' statement.
  14016.  
  14017.    You can clear an entire array using `delete ARRAY'.
  14018.  
  14019.    *Note Arrays in `awk': Arrays.
  14020.  
  14021. 
  14022. File: gawk.info,  Node: Data Type Summary,  Prev: Arrays Summary,  Up: Variables/Fields
  14023.  
  14024. Data Types
  14025. ----------
  14026.  
  14027.    The value of an `awk' expression is always either a number or a
  14028. string.
  14029.  
  14030.    Some contexts (such as arithmetic operators) require numeric values.
  14031. They convert strings to numbers by interpreting the text of the string
  14032. as a number.  If the string does not look like a number, it converts to
  14033. zero.
  14034.  
  14035.    Other contexts (such as concatenation) require string values.  They
  14036. convert numbers to strings by effectively printing them with `sprintf'.
  14037. *Note Conversion of Strings and Numbers: Conversion, for the details.
  14038.  
  14039.    To force conversion of a string value to a number, simply add zero
  14040. to it.  If the value you start with is already a number, this does not
  14041. change it.
  14042.  
  14043.    To force conversion of a numeric value to a string, concatenate it
  14044. with the null string.
  14045.  
  14046.    Comparisons are done numerically if both operands are numeric, or if
  14047. one is numeric and the other is a numeric string.  Otherwise one or
  14048. both operands are converted to strings and a string comparison is
  14049. performed.  Fields, `getline' input, `FILENAME', `ARGV' elements,
  14050. `ENVIRON' elements and the elements of an array created by `split' are
  14051. the only items that can be numeric strings. String constants, such as
  14052. `"3.1415927"' are not numeric strings, they are string constants.  The
  14053. full rules for comparisons are described in *Note Variable Typing and
  14054. Comparison Expressions: Typing and Comparison.
  14055.  
  14056.    Uninitialized variables have the string value `""' (the null, or
  14057. empty, string).  In contexts where a number is required, this is
  14058. equivalent to zero.
  14059.  
  14060.    *Note Variables::, for more information on variable naming and
  14061. initialization; *note Conversion of Strings and Numbers: Conversion.,
  14062. for more information on how variable values are interpreted.
  14063.  
  14064. 
  14065. File: gawk.info,  Node: Rules Summary,  Next: Actions Summary,  Prev: Variables/Fields,  Up: Gawk Summary
  14066.  
  14067. Patterns
  14068. ========
  14069.  
  14070. * Menu:
  14071.  
  14072. * Pattern Summary::             Quick overview of patterns.
  14073. * Regexp Summary::              Quick overview of regular expressions.
  14074.  
  14075.    An `awk' program is mostly composed of rules, each consisting of a
  14076. pattern followed by an action.  The action is enclosed in `{' and `}'.
  14077. Either the pattern may be missing, or the action may be missing, but
  14078. not both.  If the pattern is missing, the action is executed for every
  14079. input record.  A missing action is equivalent to `{ print }', which
  14080. prints the entire line.
  14081.  
  14082.    Comments begin with the `#' character, and continue until the end of
  14083. the line.  Blank lines may be used to separate statements.  Statements
  14084. normally end with a newline; however, this is not the case for lines
  14085. ending in a `,', `{', `?', `:', `&&', or `||'.  Lines ending in `do' or
  14086. `else' also have their statements automatically continued on the
  14087. following line.  In other cases, a line can be continued by ending it
  14088. with a `\', in which case the newline is ignored.
  14089.  
  14090.    Multiple statements may be put on one line by separating each one
  14091. with a `;'.  This applies to both the statements within the action part
  14092. of a rule (the usual case), and to the rule statements.
  14093.  
  14094.    *Note Comments in `awk' Programs: Comments, for information on
  14095. `awk''s commenting convention; *note `awk' Statements Versus Lines:
  14096. Statements/Lines., for a description of the line continuation mechanism
  14097. in `awk'.
  14098.  
  14099. 
  14100. File: gawk.info,  Node: Pattern Summary,  Next: Regexp Summary,  Prev: Rules Summary,  Up: Rules Summary
  14101.  
  14102. Pattern Summary
  14103. ---------------
  14104.  
  14105.    `awk' patterns may be one of the following:
  14106.  
  14107.      /REGULAR EXPRESSION/
  14108.      RELATIONAL EXPRESSION
  14109.      PATTERN && PATTERN
  14110.      PATTERN || PATTERN
  14111.      PATTERN ? PATTERN : PATTERN
  14112.      (PATTERN)
  14113.      ! PATTERN
  14114.      PATTERN1, PATTERN2
  14115.      BEGIN
  14116.      END
  14117.  
  14118.    `BEGIN' and `END' are two special kinds of patterns that are not
  14119. tested against the input.  The action parts of all `BEGIN' rules are
  14120. concatenated as if all the statements had been written in a single
  14121. `BEGIN' rule.  They are executed before any of the input is read.
  14122. Similarly, all the `END' rules are concatenated, and executed when all
  14123. the input is exhausted (or when an `exit' statement is executed).
  14124. `BEGIN' and `END' patterns cannot be combined with other patterns in
  14125. pattern expressions.  `BEGIN' and `END' rules cannot have missing
  14126. action parts.
  14127.  
  14128.    For `/REGULAR-EXPRESSION/' patterns, the associated statement is
  14129. executed for each input record that matches the regular expression.
  14130. Regular expressions are summarized below.
  14131.  
  14132.    A RELATIONAL EXPRESSION may use any of the operators defined below in
  14133. the section on actions.  These generally test whether certain fields
  14134. match certain regular expressions.
  14135.  
  14136.    The `&&', `||', and `!' operators are logical "and," logical "or,"
  14137. and logical "not," respectively, as in C.  They do short-circuit
  14138. evaluation, also as in C, and are used for combining more primitive
  14139. pattern expressions.  As in most languages, parentheses may be used to
  14140. change the order of evaluation.
  14141.  
  14142.    The `?:' operator is like the same operator in C.  If the first
  14143. pattern matches, then the second pattern is matched against the input
  14144. record; otherwise, the third is matched.  Only one of the second and
  14145. third patterns is matched.
  14146.  
  14147.    The `PATTERN1, PATTERN2' form of a pattern is called a range
  14148. pattern.  It matches all input lines starting with a line that matches
  14149. PATTERN1, and continuing until a line that matches PATTERN2, inclusive.
  14150. A range pattern cannot be used as an operand of any of the pattern
  14151. operators.
  14152.  
  14153.    *Note Pattern Elements: Pattern Overview.
  14154.  
  14155. 
  14156. File: gawk.info,  Node: Regexp Summary,  Prev: Pattern Summary,  Up: Rules Summary
  14157.  
  14158. Regular Expressions
  14159. -------------------
  14160.  
  14161.    Regular expressions are based on POSIX EREs (extended regular
  14162. expressions).  The escape sequences allowed in string constants are
  14163. also valid in regular expressions (*note Escape Sequences::.).  Regexps
  14164. are composed of characters as follows:
  14165.  
  14166. `C'
  14167.      matches the character C (assuming C is none of the characters
  14168.      listed below).
  14169.  
  14170. `\C'
  14171.      matches the literal character C.
  14172.  
  14173. `.'
  14174.      matches any character, *including* newline.  In strict POSIX mode,
  14175.      `.' does not match the NUL character, which is a character with
  14176.      all bits equal to zero.
  14177.  
  14178. `^'
  14179.      matches the beginning of a string.
  14180.  
  14181. `$'
  14182.      matches the end of a string.
  14183.  
  14184. `[ABC...]'
  14185.      matches any of the characters ABC... (character list).
  14186.  
  14187. `[[:CLASS:]]'
  14188.      matches any character in the character class CLASS. Allowable
  14189.      classes are `alnum', `alpha', `blank', `cntrl', `digit', `graph',
  14190.      `lower', `print', `punct', `space', `upper', and `xdigit'.
  14191.  
  14192. `[[.SYMBOL.]]'
  14193.      matches the multi-character collating symbol SYMBOL.  `gawk' does
  14194.      not currently support collating symbols.
  14195.  
  14196. `[[=CHARS=]]'
  14197.      matches any of the equivalent characters in CHARS.  `gawk' does
  14198.      not currently support equivalence classes.
  14199.  
  14200. `[^ABC...]'
  14201.      matches any character except ABC... and newline (negated character
  14202.      list).
  14203.  
  14204. `R1|R2'
  14205.      matches either R1 or R2 (alternation).
  14206.  
  14207. `R1R2'
  14208.      matches R1, and then R2 (concatenation).
  14209.  
  14210. `R+'
  14211.      matches one or more R's.
  14212.  
  14213. `R*'
  14214.      matches zero or more R's.
  14215.  
  14216. `R?'
  14217.      matches zero or one R's.
  14218.  
  14219. `(R)'
  14220.      matches R (grouping).
  14221.  
  14222. `R{N}'
  14223. `R{N,}'
  14224. `R{N,M}'
  14225.      matches at least N, N to any number, or N to M occurrences of R
  14226.      (interval expressions).
  14227.  
  14228. `\y'
  14229.      matches the empty string at either the beginning or the end of a
  14230.      word.
  14231.  
  14232. `\B'
  14233.      matches the empty string within a word.
  14234.  
  14235. `\<'
  14236.      matches the empty string at the beginning of a word.
  14237.  
  14238. `\>'
  14239.      matches the empty string at the end of a word.
  14240.  
  14241. `\w'
  14242.      matches any word-constituent character (alphanumeric characters and
  14243.      the underscore).
  14244.  
  14245. `\W'
  14246.      matches any character that is not word-constituent.
  14247.  
  14248. `\`'
  14249.      matches the empty string at the beginning of a buffer (same as a
  14250.      string in `gawk').
  14251.  
  14252. `\''
  14253.      matches the empty string at the end of a buffer.
  14254.  
  14255.    The various command line options control how `gawk' interprets
  14256. characters in regexps.
  14257.  
  14258. No options
  14259.      In the default case, `gawk' provide all the facilities of POSIX
  14260.      regexps and the GNU regexp operators described above.  However,
  14261.      interval expressions are not supported.
  14262.  
  14263. `--posix'
  14264.      Only POSIX regexps are supported, the GNU operators are not special
  14265.      (e.g., `\w' matches a literal `w').  Interval expressions are
  14266.      allowed.
  14267.  
  14268. `--traditional'
  14269.      Traditional Unix `awk' regexps are matched. The GNU operators are
  14270.      not special, interval expressions are not available, and neither
  14271.      are the POSIX character classes (`[[:alnum:]]' and so on).
  14272.      Characters described by octal and hexadecimal escape sequences are
  14273.      treated literally, even if they represent regexp metacharacters.
  14274.  
  14275. `--re-interval'
  14276.      Allow interval expressions in regexps, even if `--traditional' has
  14277.      been provided.
  14278.  
  14279.    *Note Regular Expressions: Regexp.
  14280.  
  14281. 
  14282. File: gawk.info,  Node: Actions Summary,  Next: Functions Summary,  Prev: Rules Summary,  Up: Gawk Summary
  14283.  
  14284. Actions
  14285. =======
  14286.  
  14287.    Action statements are enclosed in braces, `{' and `}'.  A missing
  14288. action statement is equivalent to `{ print }'.
  14289.  
  14290.    Action statements consist of the usual assignment, conditional, and
  14291. looping statements found in most languages.  The operators, control
  14292. statements, and Input/Output statements available are similar to those
  14293. in C.
  14294.  
  14295.    Comments begin with the `#' character, and continue until the end of
  14296. the line.  Blank lines may be used to separate statements.  Statements
  14297. normally end with a newline; however, this is not the case for lines
  14298. ending in a `,', `{', `?', `:', `&&', or `||'.  Lines ending in `do' or
  14299. `else' also have their statements automatically continued on the
  14300. following line.  In other cases, a line can be continued by ending it
  14301. with a `\', in which case the newline is ignored.
  14302.  
  14303.    Multiple statements may be put on one line by separating each one
  14304. with a `;'.  This applies to both the statements within the action part
  14305. of a rule (the usual case), and to the rule statements.
  14306.  
  14307.    *Note Comments in `awk' Programs: Comments, for information on
  14308. `awk''s commenting convention; *note `awk' Statements Versus Lines:
  14309. Statements/Lines., for a description of the line continuation mechanism
  14310. in `awk'.
  14311.  
  14312. * Menu:
  14313.  
  14314. * Operator Summary::            `awk' operators.
  14315. * Control Flow Summary::        The control statements.
  14316. * I/O Summary::                 The I/O statements.
  14317. * Printf Summary::              A summary of `printf'.
  14318. * Special File Summary::        Special file names interpreted internally.
  14319. * Built-in Functions Summary::  Built-in numeric and string functions.
  14320. * Time Functions Summary::      Built-in time functions.
  14321. * String Constants Summary::    Escape sequences in strings.
  14322.  
  14323. 
  14324. File: gawk.info,  Node: Operator Summary,  Next: Control Flow Summary,  Prev: Actions Summary,  Up: Actions Summary
  14325.  
  14326. Operators
  14327. ---------
  14328.  
  14329.    The operators in `awk', in order of decreasing precedence, are:
  14330.  
  14331. `(...)'
  14332.      Grouping.
  14333.  
  14334. `$'
  14335.      Field reference.
  14336.  
  14337. `++ --'
  14338.      Increment and decrement, both prefix and postfix.
  14339.  
  14340. `^'
  14341.      Exponentiation (`**' may also be used, and `**=' for the assignment
  14342.      operator, but they are not specified in the POSIX standard).
  14343.  
  14344. `+ - !'
  14345.      Unary plus, unary minus, and logical negation.
  14346.  
  14347. `* / %'
  14348.      Multiplication, division, and modulus.
  14349.  
  14350. `+ -'
  14351.      Addition and subtraction.
  14352.  
  14353. `SPACE'
  14354.      String concatenation.
  14355.  
  14356. `< <= > >= != =='
  14357.      The usual relational operators.
  14358.  
  14359. `~ !~'
  14360.      Regular expression match, negated match.
  14361.  
  14362. `in'
  14363.      Array membership.
  14364.  
  14365. `&&'
  14366.      Logical "and".
  14367.  
  14368. `||'
  14369.      Logical "or".
  14370.  
  14371. `?:'
  14372.      A conditional expression.  This has the form `EXPR1 ?  EXPR2 :
  14373.      EXPR3'.  If EXPR1 is true, the value of the expression is EXPR2;
  14374.      otherwise it is EXPR3.  Only one of EXPR2 and EXPR3 is evaluated.
  14375.  
  14376. `= += -= *= /= %= ^='
  14377.      Assignment.  Both absolute assignment (`VAR=VALUE') and operator
  14378.      assignment (the other forms) are supported.
  14379.  
  14380.    *Note Expressions::.
  14381.  
  14382. 
  14383. File: gawk.info,  Node: Control Flow Summary,  Next: I/O Summary,  Prev: Operator Summary,  Up: Actions Summary
  14384.  
  14385. Control Statements
  14386. ------------------
  14387.  
  14388.    The control statements are as follows:
  14389.  
  14390.      if (CONDITION) STATEMENT [ else STATEMENT ]
  14391.      while (CONDITION) STATEMENT
  14392.      do STATEMENT while (CONDITION)
  14393.      for (EXPR1; EXPR2; EXPR3) STATEMENT
  14394.      for (VAR in ARRAY) STATEMENT
  14395.      break
  14396.      continue
  14397.      delete ARRAY[INDEX]
  14398.      delete ARRAY
  14399.      exit [ EXPRESSION ]
  14400.      { STATEMENTS }
  14401.  
  14402.    *Note Control Statements in Actions: Statements.
  14403.  
  14404. 
  14405. File: gawk.info,  Node: I/O Summary,  Next: Printf Summary,  Prev: Control Flow Summary,  Up: Actions Summary
  14406.  
  14407. I/O Statements
  14408. --------------
  14409.  
  14410.    The Input/Output statements are as follows:
  14411.  
  14412. `getline'
  14413.      Set `$0' from next input record; set `NF', `NR', `FNR'.  *Note
  14414.      Explicit Input with `getline': Getline.
  14415.  
  14416. `getline <FILE'
  14417.      Set `$0' from next record of FILE; set `NF'.
  14418.  
  14419. `getline VAR'
  14420.      Set VAR from next input record; set `NF', `FNR'.
  14421.  
  14422. `getline VAR <FILE'
  14423.      Set VAR from next record of FILE.
  14424.  
  14425. `COMMAND | getline'
  14426.      Run COMMAND, piping its output into `getline'; sets `$0', `NF',
  14427.      `NR'.
  14428.  
  14429. `COMMAND | getline `var''
  14430.      Run COMMAND, piping its output into `getline'; sets VAR.
  14431.  
  14432. `next'
  14433.      Stop processing the current input record.  The next input record
  14434.      is read and processing starts over with the first pattern in the
  14435.      `awk' program.  If the end of the input data is reached, the `END'
  14436.      rule(s), if any, are executed.  *Note The `next' Statement: Next
  14437.      Statement.
  14438.  
  14439. `nextfile'
  14440.      Stop processing the current input file.  The next input record
  14441.      read comes from the next input file.  `FILENAME' is updated, `FNR'
  14442.      is set to one, `ARGIND' is incremented, and processing starts over
  14443.      with the first pattern in the `awk' program.  If the end of the
  14444.      input data is reached, the `END' rule(s), if any, are executed.
  14445.      Earlier versions of `gawk' used `next file'; this usage is still
  14446.      supported, but is considered to be deprecated.  *Note The
  14447.      `nextfile' Statement: Nextfile Statement.
  14448.  
  14449. `print'
  14450.      Prints the current record.  *Note Printing Output: Printing.
  14451.  
  14452. `print EXPR-LIST'
  14453.      Prints expressions.
  14454.  
  14455. `print EXPR-LIST > FILE'
  14456.      Prints expressions to FILE. If FILE does not exist, it is created.
  14457.      If it does exist, its contents are deleted the first time the
  14458.      `print' is executed.
  14459.  
  14460. `print EXPR-LIST >> FILE'
  14461.      Prints expressions to FILE.  The previous contents of FILE are
  14462.      retained, and the output of `print' is appended to the file.
  14463.  
  14464. `print EXPR-LIST | COMMAND'
  14465.      Prints expressions, sending the output down a pipe to COMMAND.
  14466.      The pipeline to the command stays open until the `close' function
  14467.      is called.
  14468.  
  14469. `printf FMT, EXPR-LIST'
  14470.      Format and print.
  14471.  
  14472. `printf FMT, EXPR-LIST > file'
  14473.      Format and print to FILE. If FILE does not exist, it is created.
  14474.      If it does exist, its contents are deleted the first time the
  14475.      `printf' is executed.
  14476.  
  14477. `printf FMT, EXPR-LIST >> FILE'
  14478.      Format and print to FILE.  The previous contents of FILE are
  14479.      retained, and the output of `printf' is appended to the file.
  14480.  
  14481. `printf FMT, EXPR-LIST | COMMAND'
  14482.      Format and print, sending the output down a pipe to COMMAND.  The
  14483.      pipeline to the command stays open until the `close' function is
  14484.      called.
  14485.  
  14486.    `getline' returns zero on end of file, and -1 on an error.  In the
  14487. event of an error, `getline' will set `ERRNO' to the value of a
  14488. system-dependent string that describes the error.
  14489.  
  14490. 
  14491. File: gawk.info,  Node: Printf Summary,  Next: Special File Summary,  Prev: I/O Summary,  Up: Actions Summary
  14492.  
  14493. `printf' Summary
  14494. ----------------
  14495.  
  14496.    Conversion specification have the form
  14497. `%'[FLAG][WIDTH][`.'PREC]FORMAT.  Items in brackets are optional.
  14498.  
  14499.    The `awk' `printf' statement and `sprintf' function accept the
  14500. following conversion specification formats:
  14501.  
  14502. `%c'
  14503.      An ASCII character.  If the argument used for `%c' is numeric, it
  14504.      is treated as a character and printed.  Otherwise, the argument is
  14505.      assumed to be a string, and the only first character of that
  14506.      string is printed.
  14507.  
  14508. `%d'
  14509. `%i'
  14510.      A decimal number (the integer part).
  14511.  
  14512. `%e'
  14513. `%E'
  14514.      A floating point number of the form `[-]d.dddddde[+-]dd'.  The
  14515.      `%E' format uses `E' instead of `e'.
  14516.  
  14517. `%f'
  14518.      A floating point number of the form [`-']`ddd.dddddd'.
  14519.  
  14520. `%g'
  14521. `%G'
  14522.      Use either the `%e' or `%f' formats, whichever produces a shorter
  14523.      string, with non-significant zeros suppressed.  `%G' will use `%E'
  14524.      instead of `%e'.
  14525.  
  14526. `%o'
  14527.      An unsigned octal number (again, an integer).
  14528.  
  14529. `%s'
  14530.      A character string.
  14531.  
  14532. `%x'
  14533. `%X'
  14534.      An unsigned hexadecimal number (an integer).  The `%X' format uses
  14535.      `A' through `F' instead of `a' through `f' for decimal 10 through
  14536.      15.
  14537.  
  14538. `%%'
  14539.      A single `%' character; no argument is converted.
  14540.  
  14541.    There are optional, additional parameters that may lie between the
  14542. `%' and the control letter:
  14543.  
  14544. `-'
  14545.      The expression should be left-justified within its field.
  14546.  
  14547. `SPACE'
  14548.      For numeric conversions, prefix positive values with a space, and
  14549.      negative values with a minus sign.
  14550.  
  14551. `+'
  14552.      The plus sign, used before the width modifier (see below), says to
  14553.      always supply a sign for numeric conversions, even if the data to
  14554.      be formatted is positive. The `+' overrides the space modifier.
  14555.  
  14556. `#'
  14557.      Use an "alternate form" for certain control letters.  For `o',
  14558.      supply a leading zero.  For `x', and `X', supply a leading `0x' or
  14559.      `0X' for a non-zero result.  For `e', `E', and `f', the result
  14560.      will always contain a decimal point.  For `g', and `G', trailing
  14561.      zeros are not removed from the result.
  14562.  
  14563. `0'
  14564.      A leading `0' (zero) acts as a flag, that indicates output should
  14565.      be padded with zeros instead of spaces.  This applies even to
  14566.      non-numeric output formats.  This flag only has an effect when the
  14567.      field width is wider than the value to be printed.
  14568.  
  14569. `WIDTH'
  14570.      The field should be padded to this width. The field is normally
  14571.      padded with spaces.  If the `0' flag has been used, it is padded
  14572.      with zeros.
  14573.  
  14574. `.PREC'
  14575.      A number that specifies the precision to use when printing.  For
  14576.      the `e', `E', and `f' formats, this specifies the number of digits
  14577.      you want printed to the right of the decimal point.  For the `g',
  14578.      and `G' formats, it specifies the maximum number of significant
  14579.      digits.  For the `d', `o', `i', `u', `x', and `X' formats, it
  14580.      specifies the minimum number of digits to print.  For the `s'
  14581.      format, it specifies the maximum number of characters from the
  14582.      string that should be printed.
  14583.  
  14584.    Either or both of the WIDTH and PREC values may be specified as `*'.
  14585. In that case, the particular value is taken from the argument list.
  14586.  
  14587.    *Note Using `printf' Statements for Fancier Printing: Printf.
  14588.  
  14589. 
  14590. File: gawk.info,  Node: Special File Summary,  Next: Built-in Functions Summary,  Prev: Printf Summary,  Up: Actions Summary
  14591.  
  14592. Special File Names
  14593. ------------------
  14594.  
  14595.    When doing I/O redirection from either `print' or `printf' into a
  14596. file, or via `getline' from a file, `gawk' recognizes certain special
  14597. file names internally.  These file names allow access to open file
  14598. descriptors inherited from `gawk''s parent process (usually the shell).
  14599. The file names are:
  14600.  
  14601. `/dev/stdin'
  14602.      The standard input.
  14603.  
  14604. `/dev/stdout'
  14605.      The standard output.
  14606.  
  14607. `/dev/stderr'
  14608.      The standard error output.
  14609.  
  14610. `/dev/fd/N'
  14611.      The file denoted by the open file descriptor N.
  14612.  
  14613.    In addition, reading the following files provides process related
  14614. information about the running `gawk' program.  All returned records are
  14615. terminated with a newline.
  14616.  
  14617. `/dev/pid'
  14618.      Returns the process ID of the current process.
  14619.  
  14620. `/dev/ppid'
  14621.      Returns the parent process ID of the current process.
  14622.  
  14623. `/dev/pgrpid'
  14624.      Returns the process group ID of the current process.
  14625.  
  14626. `/dev/user'
  14627.      At least four space-separated fields, containing the return values
  14628.      of the `getuid', `geteuid', `getgid', and `getegid' system calls.
  14629.      If there are any additional fields, they are the group IDs
  14630.      returned by `getgroups' system call.  (Multiple groups may not be
  14631.      supported on all systems.)
  14632.  
  14633. These file names may also be used on the command line to name data
  14634. files.  These file names are only recognized internally if you do not
  14635. actually have files with these names on your system.
  14636.  
  14637.    *Note Special File Names in `gawk': Special Files, for a longer
  14638. description that provides the motivation for this feature.
  14639.  
  14640. 
  14641. File: gawk.info,  Node: Built-in Functions Summary,  Next: Time Functions Summary,  Prev: Special File Summary,  Up: Actions Summary
  14642.  
  14643. Built-in Functions
  14644. ------------------
  14645.  
  14646.    `awk' provides a number of built-in functions for performing numeric
  14647. operations, string related operations, and I/O related operations.
  14648.  
  14649.    The built-in arithmetic functions are:
  14650.  
  14651. `atan2(Y, X)'
  14652.      the arctangent of Y/X in radians.
  14653.  
  14654. `cos(EXPR)'
  14655.      the cosine in radians.
  14656.  
  14657. `exp(EXPR)'
  14658.      the exponential function (`e ^ EXPR').
  14659.  
  14660. `int(EXPR)'
  14661.      truncates to integer.
  14662.  
  14663. `log(EXPR)'
  14664.      the natural logarithm of `expr'.
  14665.  
  14666. `rand()'
  14667.      a random number between zero and one.
  14668.  
  14669. `sin(EXPR)'
  14670.      the sine in radians.
  14671.  
  14672. `sqrt(EXPR)'
  14673.      the square root function.
  14674.  
  14675. `srand([EXPR])'
  14676.      use EXPR as a new seed for the random number generator.  If no EXPR
  14677.      is provided, the time of day is used.  The return value is the
  14678.      previous seed for the random number generator.
  14679.  
  14680.    `awk' has the following built-in string functions:
  14681.  
  14682. `gensub(REGEX, SUBST, HOW [, TARGET])'
  14683.      If HOW is a string beginning with `g' or `G', then replace each
  14684.      match of REGEX in TARGET with SUBST.  Otherwise, replace the
  14685.      HOW'th occurrence. If TARGET is not supplied, use `$0'.  The
  14686.      return value is the changed string; the original TARGET is not
  14687.      modified. Within SUBST, `\N', where N is a digit from one to nine,
  14688.      can be used to indicate the text that matched the N'th
  14689.      parenthesized subexpression.
  14690.  
  14691. `gsub(REGEX, SUBST [, TARGET])'
  14692.      for each substring matching the regular expression REGEX in the
  14693.      string TARGET, substitute the string SUBST, and return the number
  14694.      of substitutions. If TARGET is not supplied, use `$0'.
  14695.  
  14696. `index(STR, SEARCH)'
  14697.      returns the index of the string SEARCH in the string STR, or zero
  14698.      if SEARCH is not present.
  14699.  
  14700. `length([STR])'
  14701.      returns the length of the string STR.  The length of `$0' is
  14702.      returned if no argument is supplied.
  14703.  
  14704. `match(STR, REGEX)'
  14705.      returns the position in STR where the regular expression REGEX
  14706.      occurs, or zero if REGEX is not present, and sets the values of
  14707.      `RSTART' and `RLENGTH'.
  14708.  
  14709. `split(STR, ARR [, REGEX])'
  14710.      splits the string STR into the array ARR on the regular expression
  14711.      REGEX, and returns the number of elements.  If REGEX is omitted,
  14712.      `FS' is used instead. REGEX can be the null string, causing each
  14713.      character to be placed into its own array element.  The array ARR
  14714.      is cleared first.
  14715.  
  14716. `sprintf(FMT, EXPR-LIST)'
  14717.      prints EXPR-LIST according to FMT, and returns the resulting
  14718.      string.
  14719.  
  14720. `sub(REGEX, SUBST [, TARGET])'
  14721.      just like `gsub', but only the first matching substring is
  14722.      replaced.
  14723.  
  14724. `substr(STR, INDEX [, LEN])'
  14725.      returns the LEN-character substring of STR starting at INDEX.  If
  14726.      LEN is omitted, the rest of STR is used.
  14727.  
  14728. `tolower(STR)'
  14729.      returns a copy of the string STR, with all the upper-case
  14730.      characters in STR translated to their corresponding lower-case
  14731.      counterparts.  Non-alphabetic characters are left unchanged.
  14732.  
  14733. `toupper(STR)'
  14734.      returns a copy of the string STR, with all the lower-case
  14735.      characters in STR translated to their corresponding upper-case
  14736.      counterparts.  Non-alphabetic characters are left unchanged.
  14737.  
  14738.    The I/O related functions are:
  14739.  
  14740. `close(EXPR)'
  14741.      Close the open file or pipe denoted by EXPR.
  14742.  
  14743. `fflush([EXPR])'
  14744.      Flush any buffered output for the output file or pipe denoted by
  14745.      EXPR.  If EXPR is omitted, standard output is flushed.  If EXPR is
  14746.      the null string (`""'), all output buffers are flushed.
  14747.  
  14748. `system(CMD-LINE)'
  14749.      Execute the command CMD-LINE, and return the exit status.  If your
  14750.      operating system does not support `system', calling it will
  14751.      generate a fatal error.
  14752.  
  14753.      `system("")' can be used to force `awk' to flush any pending
  14754.      output.  This is more portable, but less obvious, than calling
  14755.      `fflush'.
  14756.  
  14757. 
  14758. File: gawk.info,  Node: Time Functions Summary,  Next: String Constants Summary,  Prev: Built-in Functions Summary,  Up: Actions Summary
  14759.  
  14760. Time Functions
  14761. --------------
  14762.  
  14763.    The following two functions are available for getting the current
  14764. time of day, and for formatting time stamps.
  14765.  
  14766. `systime()'
  14767.      returns the current time of day as the number of seconds since a
  14768.      particular epoch (Midnight, January 1, 1970 UTC, on POSIX systems).
  14769.  
  14770. `strftime([FORMAT[, TIMESTAMP]])'
  14771.      formats TIMESTAMP according to the specification in FORMAT.  The
  14772.      current time of day is used if no TIMESTAMP is supplied.  A
  14773.      default format equivalent to the output of the `date' utility is
  14774.      used if no FORMAT is supplied.  *Note Functions for Dealing with
  14775.      Time Stamps: Time Functions, for the details on the conversion
  14776.      specifiers that `strftime' accepts.
  14777.  
  14778. 
  14779. File: gawk.info,  Node: String Constants Summary,  Prev: Time Functions Summary,  Up: Actions Summary
  14780.  
  14781. String Constants
  14782. ----------------
  14783.  
  14784.    String constants in `awk' are sequences of characters enclosed in
  14785. double quotes (`"').  Within strings, certain "escape sequences" are
  14786. recognized, as in C.  These are:
  14787.  
  14788. `\\'
  14789.      A literal backslash.
  14790.  
  14791. `\a'
  14792.      The "alert" character; usually the ASCII BEL character.
  14793.  
  14794. `\b'
  14795.      Backspace.
  14796.  
  14797. `\f'
  14798.      Formfeed.
  14799.  
  14800. `\n'
  14801.      Newline.
  14802.  
  14803. `\r'
  14804.      Carriage return.
  14805.  
  14806. `\t'
  14807.      Horizontal tab.
  14808.  
  14809. `\v'
  14810.      Vertical tab.
  14811.  
  14812. `\xHEX DIGITS'
  14813.      The character represented by the string of hexadecimal digits
  14814.      following the `\x'.  As in ANSI C, all following hexadecimal
  14815.      digits are considered part of the escape sequence.  E.g., `"\x1B"'
  14816.      is a string containing the ASCII ESC (escape) character.  (The `\x'
  14817.      escape sequence is not in POSIX `awk'.)
  14818.  
  14819. `\DDD'
  14820.      The character represented by the one, two, or three digit sequence
  14821.      of octal digits.  Thus, `"\033"' is also a string containing the
  14822.      ASCII ESC (escape) character.
  14823.  
  14824. `\C'
  14825.      The literal character C, if C is not one of the above.
  14826.  
  14827.    The escape sequences may also be used inside constant regular
  14828. expressions (e.g., the regexp `/[ \t\f\n\r\v]/' matches whitespace
  14829. characters).
  14830.  
  14831.    *Note Escape Sequences::.
  14832.  
  14833. 
  14834. File: gawk.info,  Node: Functions Summary,  Next: Historical Features,  Prev: Actions Summary,  Up: Gawk Summary
  14835.  
  14836. User-defined Functions
  14837. ======================
  14838.  
  14839.    Functions in `awk' are defined as follows:
  14840.  
  14841.      function NAME(PARAMETER LIST) { STATEMENTS }
  14842.  
  14843.    Actual parameters supplied in the function call are used to
  14844. instantiate the formal parameters declared in the function.  Arrays are
  14845. passed by reference, other variables are passed by value.
  14846.  
  14847.    If there are fewer arguments passed than there are names in
  14848. PARAMETER-LIST, the extra names are given the null string as their
  14849. value.  Extra names have the effect of local variables.
  14850.  
  14851.    The open-parenthesis in a function call of a user-defined function
  14852. must immediately follow the function name, without any intervening
  14853. white space.  This is to avoid a syntactic ambiguity with the
  14854. concatenation operator.
  14855.  
  14856.    The word `func' may be used in place of `function' (but not in POSIX
  14857. `awk').
  14858.  
  14859.    Use the `return' statement to return a value from a function.
  14860.  
  14861.    *Note User-defined Functions: User-defined.
  14862.  
  14863. 
  14864. File: gawk.info,  Node: Historical Features,  Prev: Functions Summary,  Up: Gawk Summary
  14865.  
  14866. Historical Features
  14867. ===================
  14868.  
  14869.    There are two features of historical `awk' implementations that
  14870. `gawk' supports.
  14871.  
  14872.    First, it is possible to call the `length' built-in function not only
  14873. with no arguments, but even without parentheses!
  14874.  
  14875.      a = length
  14876.  
  14877. is the same as either of
  14878.  
  14879.      a = length()
  14880.      a = length($0)
  14881.  
  14882. For example:
  14883.  
  14884.      $ echo abcdef | awk '{ print length }'
  14885.      -| 6
  14886.  
  14887. This feature is marked as "deprecated" in the POSIX standard, and
  14888. `gawk' will issue a warning about its use if `--lint' is specified on
  14889. the command line.  (The ability to use `length' this way was actually
  14890. an accident of the original Unix `awk' implementation.  If any built-in
  14891. function used `$0' as its default argument, it was possible to call
  14892. that function without the parentheses.  In particular, it was common
  14893. practice to use the `length' function in this fashion, and this usage
  14894. was documented in the `awk' manual page.)
  14895.  
  14896.    The other historical feature is the use of either the `break'
  14897. statement, or the `continue' statement outside the body of a `while',
  14898. `for', or `do' loop.  Traditional `awk' implementations have treated
  14899. such usage as equivalent to the `next' statement.  More recent versions
  14900. of Unix `awk' do not allow it. `gawk' supports this usage if
  14901. `--traditional' has been specified.
  14902.  
  14903.    *Note Command Line Options: Options, for more information about the
  14904. `--posix' and `--lint' options.
  14905.  
  14906. 
  14907. File: gawk.info,  Node: Installation,  Next: Notes,  Prev: Gawk Summary,  Up: Top
  14908.  
  14909. Installing `gawk'
  14910. *****************
  14911.  
  14912.    This appendix provides instructions for installing `gawk' on the
  14913. various platforms that are supported by the developers.  The primary
  14914. developers support Unix (and one day, GNU), while the other ports were
  14915. contributed.  The file `ACKNOWLEDGMENT' in the `gawk' distribution
  14916. lists the electronic mail addresses of the people who did the
  14917. respective ports, and they are also provided in *Note Reporting
  14918. Problems and Bugs: Bugs.
  14919.  
  14920. * Menu:
  14921.  
  14922. * Gawk Distribution::           What is in the `gawk' distribution.
  14923. * Unix Installation::           Installing `gawk' under various versions
  14924.                                 of Unix.
  14925. * VMS Installation::            Installing `gawk' on VMS.
  14926. * PC Installation::             Installing and Compiling `gawk' on MS-DOS
  14927.                                 and OS/2
  14928. * Atari Installation::          Installing `gawk' on the Atari ST.
  14929. * Amiga Installation::          Installing `gawk' on an Amiga.
  14930. * Bugs::                        Reporting Problems and Bugs.
  14931. * Other Versions::              Other freely available `awk'
  14932.                                 implementations.
  14933.  
  14934. 
  14935. File: gawk.info,  Node: Gawk Distribution,  Next: Unix Installation,  Prev: Installation,  Up: Installation
  14936.  
  14937. The `gawk' Distribution
  14938. =======================
  14939.  
  14940.    This section first describes how to get the `gawk' distribution, how
  14941. to extract it, and then what is in the various files and subdirectories.
  14942.  
  14943. * Menu:
  14944.  
  14945. * Getting::                     How to get the distribution.
  14946. * Extracting::                  How to extract the distribution.
  14947. * Distribution contents::       What is in the distribution.
  14948.  
  14949. 
  14950. File: gawk.info,  Node: Getting,  Next: Extracting,  Prev: Gawk Distribution,  Up: Gawk Distribution
  14951.  
  14952. Getting the `gawk' Distribution
  14953. -------------------------------
  14954.  
  14955.    There are three ways you can get GNU software.
  14956.  
  14957.   1. You can copy it from someone else who already has it.
  14958.  
  14959.   2. You can order `gawk' directly from the Free Software Foundation.
  14960.      Software distributions are available for Unix, MS-DOS, and VMS, on
  14961.      tape, CD-ROM, or floppies (MS-DOS only).  The address is:
  14962.  
  14963.           Free Software Foundation
  14964.           59 Temple Place--Suite 330
  14965.           Boston, MA  02111-1307 USA
  14966.           Phone: +1-617-542-5942
  14967.           Fax (including Japan): +1-617-542-2652
  14968.           E-mail: `gnu@prep.ai.mit.edu'
  14969.  
  14970.      Ordering from the FSF directly contributes to the support of the
  14971.      foundation and to the production of more free software.
  14972.  
  14973.   3. You can get `gawk' by using anonymous `ftp' to the Internet host
  14974.      `ftp.gnu.ai.mit.edu', in the directory `/pub/gnu'.
  14975.  
  14976.      Here is a list of alternate `ftp' sites from which you can obtain
  14977.      GNU software.  When a site is listed as "SITE`:'DIRECTORY" the
  14978.      DIRECTORY indicates the directory where GNU software is kept.  You
  14979.      should use a site that is geographically close to you.
  14980.  
  14981.     Asia:
  14982.          `cair-archive.kaist.ac.kr:/pub/gnu'
  14983.          `ftp.cs.titech.ac.jp'
  14984.          `ftp.nectec.or.th:/pub/mirrors/gnu'
  14985.          `utsun.s.u-tokyo.ac.jp:/ftpsync/prep'
  14986.     Australia:
  14987.          `archie.au:/gnu'
  14988.                (`archie.oz' or `archie.oz.au' for ACSnet)
  14989.  
  14990.     Africa:
  14991.          `ftp.sun.ac.za:/pub/gnu'
  14992.     Middle East:
  14993.          `ftp.technion.ac.il:/pub/unsupported/gnu'
  14994.     Europe:
  14995.          `archive.eu.net'
  14996.          `ftp.denet.dk'
  14997.          `ftp.eunet.ch'
  14998.          `ftp.funet.fi:/pub/gnu'
  14999.          `ftp.ieunet.ie:pub/gnu'
  15000.          `ftp.informatik.rwth-aachen.de:/pub/gnu'
  15001.          `ftp.informatik.tu-muenchen.de'
  15002.          `ftp.luth.se:/pub/unix/gnu'
  15003.          `ftp.mcc.ac.uk'
  15004.          `ftp.stacken.kth.se'
  15005.          `ftp.sunet.se:/pub/gnu'
  15006.          `ftp.univ-lyon1.fr:pub/gnu'
  15007.          `ftp.win.tue.nl:/pub/gnu'
  15008.          `irisa.irisa.fr:/pub/gnu'
  15009.          `isy.liu.se'
  15010.          `nic.switch.ch:/mirror/gnu'
  15011.          `src.doc.ic.ac.uk:/gnu'
  15012.          `unix.hensa.ac.uk:/pub/uunet/systems/gnu'
  15013.     South America:
  15014.          `ftp.inf.utfsm.cl:/pub/gnu'
  15015.          `ftp.unicamp.br:/pub/gnu'
  15016.     Western Canada:
  15017.          `ftp.cs.ubc.ca:/mirror2/gnu'
  15018.     USA:
  15019.          `col.hp.com:/mirrors/gnu'
  15020.          `f.ms.uky.edu:/pub3/gnu'
  15021.          `ftp.cc.gatech.edu:/pub/gnu'
  15022.          `ftp.cs.columbia.edu:/archives/gnu/prep'
  15023.          `ftp.digex.net:/pub/gnu'
  15024.          `ftp.hawaii.edu:/mirrors/gnu'
  15025.          `ftp.kpc.com:/pub/mirror/gnu'
  15026.     USA (continued):
  15027.          `ftp.uu.net:/systems/gnu'
  15028.          `gatekeeper.dec.com:/pub/GNU'
  15029.          `jaguar.utah.edu:/gnustuff'
  15030.          `labrea.stanford.edu'
  15031.          `mrcnext.cso.uiuc.edu:/pub/gnu'
  15032.          `vixen.cso.uiuc.edu:/gnu'
  15033.          `wuarchive.wustl.edu:/systems/gnu'
  15034.  
  15035. 
  15036. File: gawk.info,  Node: Extracting,  Next: Distribution contents,  Prev: Getting,  Up: Gawk Distribution
  15037.  
  15038. Extracting the Distribution
  15039. ---------------------------
  15040.  
  15041.    `gawk' is distributed as a `tar' file compressed with the GNU Zip
  15042. program, `gzip'.
  15043.  
  15044.    Once you have the distribution (for example, `gawk-3.0.0.tar.gz'),
  15045. first use `gzip' to expand the file, and then use `tar' to extract it.
  15046. You can use the following pipeline to produce the `gawk' distribution:
  15047.  
  15048.      # Under System V, add 'o' to the tar flags
  15049.      gzip -d -c gawk-3.0.0.tar.gz | tar -xvpf -
  15050.  
  15051. This will create a directory named `gawk-3.0.0' in the current
  15052. directory.
  15053.  
  15054.    The distribution file name is of the form `gawk-V.R.N.tar.gz'.  The
  15055. V represents the major version of `gawk', the R represents the current
  15056. release of version V, and the N represents a "patch level", meaning
  15057. that minor bugs have been fixed in the release.  The current patch
  15058. level is 0, but when retrieving distributions, you should get the
  15059. version with the highest version, release, and patch level.  (Note that
  15060. release levels greater than or equal to 90 denote "beta," or
  15061. non-production software; you may not wish to retrieve such a version
  15062. unless you don't mind experimenting.)
  15063.  
  15064.    If you are not on a Unix system, you will need to make other
  15065. arrangements for getting and extracting the `gawk' distribution.  You
  15066. should consult a local expert.
  15067.  
  15068. 
  15069. File: gawk.info,  Node: Distribution contents,  Prev: Extracting,  Up: Gawk Distribution
  15070.  
  15071. Contents of the `gawk' Distribution
  15072. -----------------------------------
  15073.  
  15074.    The `gawk' distribution has a number of C source files,
  15075. documentation files, subdirectories and files related to the
  15076. configuration process (*note Compiling and Installing `gawk' on Unix:
  15077. Unix Installation.), and several subdirectories related to different,
  15078. non-Unix, operating systems.
  15079.  
  15080. various `.c', `.y', and `.h' files
  15081.      These files are the actual `gawk' source code.
  15082.  
  15083. `README'
  15084. `README_d/README.*'
  15085.      Descriptive files: `README' for `gawk' under Unix, and the rest
  15086.      for the various hardware and software combinations.
  15087.  
  15088. `INSTALL'
  15089.      A file providing an overview of the configuration and installation
  15090.      process.
  15091.  
  15092. `PORTS'
  15093.      A list of systems to which `gawk' has been ported, and which have
  15094.      successfully run the test suite.
  15095.  
  15096. `ACKNOWLEDGMENT'
  15097.      A list of the people who contributed major parts of the code or
  15098.      documentation.
  15099.  
  15100. `ChangeLog'
  15101.      A detailed list of source code changes as bugs are fixed or
  15102.      improvements made.
  15103.  
  15104. `NEWS'
  15105.      A list of changes to `gawk' since the last release or patch.
  15106.  
  15107. `COPYING'
  15108.      The GNU General Public License.
  15109.  
  15110. `FUTURES'
  15111.      A brief list of features and/or changes being contemplated for
  15112.      future releases, with some indication of the time frame for the
  15113.      feature, based on its difficulty.
  15114.  
  15115. `LIMITATIONS'
  15116.      A list of those factors that limit `gawk''s performance.  Most of
  15117.      these depend on the hardware or operating system software, and are
  15118.      not limits in `gawk' itself.
  15119.  
  15120. `POSIX.STD'
  15121.      A description of one area where the POSIX standard for `awk' is
  15122.      incorrect, and how `gawk' handles the problem.
  15123.  
  15124. `PROBLEMS'
  15125.      A file describing known problems with the current release.
  15126.  
  15127. `doc/gawk.1'
  15128.      The `troff' source for a manual page describing `gawk'.  This is
  15129.      distributed for the convenience of Unix users.
  15130.  
  15131. `doc/gawk.texi'
  15132.      The Texinfo source file for this Info file.  It should be
  15133.      processed with TeX to produce a printed document, and with
  15134.      `makeinfo' to produce an Info file.
  15135.  
  15136. `doc/gawk.info'
  15137.      The generated Info file for this Info file.
  15138.  
  15139. `doc/igawk.1'
  15140.      The `troff' source for a manual page describing the `igawk'
  15141.      program presented in *Note An Easy Way to Use Library Functions:
  15142.      Igawk Program.
  15143.  
  15144. `doc/Makefile.in'
  15145.      The input file used during the configuration process to generate
  15146.      the actual `Makefile' for creating the documentation.
  15147.  
  15148. `Makefile.in'
  15149. `acconfig.h'
  15150. `aclocal.m4'
  15151. `configh.in'
  15152. `configure.in'
  15153. `configure'
  15154. `custom.h'
  15155. `missing/*'
  15156.      These files and subdirectory are used when configuring `gawk' for
  15157.      various Unix systems.  They are explained in detail in *Note
  15158.      Compiling and Installing `gawk' on Unix: Unix Installation.
  15159.  
  15160. `awklib/extract.awk'
  15161. `awklib/Makefile.in'
  15162.      The `awklib' directory contains a copy of `extract.awk' (*note
  15163.      Extracting Programs from Texinfo Source Files: Extract Program.),
  15164.      which can be used to extract the sample programs from the Texinfo
  15165.      source file for this Info file, and a `Makefile.in' file, which
  15166.      `configure' uses to generate a `Makefile'.  As part of the process
  15167.      of building `gawk', the library functions from *Note A Library of
  15168.      `awk' Functions: Library Functions, and the `igawk' program from
  15169.      *Note An Easy Way to Use Library Functions: Igawk Program, are
  15170.      extracted into ready to use files.  They are installed as part of
  15171.      the installation process.
  15172.  
  15173. `amiga/*'
  15174.      Files needed for building `gawk' on an Amiga.  *Note Installing
  15175.      `gawk' on an Amiga: Amiga Installation, for details.
  15176.  
  15177. `atari/*'
  15178.      Files needed for building `gawk' on an Atari ST.  *Note Installing
  15179.      `gawk' on the Atari ST: Atari Installation, for details.
  15180.  
  15181. `pc/*'
  15182.      Files needed for building `gawk' under MS-DOS and OS/2.  *Note
  15183.      MS-DOS and OS/2 Installation and Compilation: PC Installation, for
  15184.      details.
  15185.  
  15186. `vms/*'
  15187.      Files needed for building `gawk' under VMS.  *Note How to Compile
  15188.      and Install `gawk' on VMS: VMS Installation, for details.
  15189.  
  15190. `test/*'
  15191.      A test suite for `gawk'.  You can use `make check' from the top
  15192.      level `gawk' directory to run your version of `gawk' against the
  15193.      test suite.  If `gawk' successfully passes `make check' then you
  15194.      can be confident of a successful port.
  15195.  
  15196. 
  15197. File: gawk.info,  Node: Unix Installation,  Next: VMS Installation,  Prev: Gawk Distribution,  Up: Installation
  15198.  
  15199. Compiling and Installing `gawk' on Unix
  15200. =======================================
  15201.  
  15202.    Usually, you can compile and install `gawk' by typing only two
  15203. commands.  However, if you do use an unusual system, you may need to
  15204. configure `gawk' for your system yourself.
  15205.  
  15206. * Menu:
  15207.  
  15208. * Quick Installation::          Compiling `gawk' under Unix.
  15209. * Configuration Philosophy::    How it's all supposed to work.
  15210.  
  15211. 
  15212. File: gawk.info,  Node: Quick Installation,  Next: Configuration Philosophy,  Prev: Unix Installation,  Up: Unix Installation
  15213.  
  15214. Compiling `gawk' for Unix
  15215. -------------------------
  15216.  
  15217.    After you have extracted the `gawk' distribution, `cd' to
  15218. `gawk-3.0.0'.  Like most GNU software, `gawk' is configured
  15219. automatically for your Unix system by running the `configure' program.
  15220. This program is a Bourne shell script that was generated automatically
  15221. using GNU `autoconf'.  (The `autoconf' software is described fully
  15222. starting with *Note Introduction: (autoconf)Top.)
  15223.  
  15224.    To configure `gawk', simply run `configure':
  15225.  
  15226.      sh ./configure
  15227.  
  15228.    This produces a `Makefile' and `config.h' tailored to your system.
  15229. The `config.h' file describes various facts about your system.  You may
  15230. wish to edit the `Makefile' to change the `CFLAGS' variable, which
  15231. controls the command line options that are passed to the C compiler
  15232. (such as optimization levels, or compiling for debugging).
  15233.  
  15234.    Alternatively, you can add your own values for most `make'
  15235. variables, such as `CC' and `CFLAGS', on the command line when running
  15236. `configure':
  15237.  
  15238.      CC=cc CFLAGS=-g sh ./configure
  15239.  
  15240. See the file `INSTALL' in the `gawk' distribution for all the details.
  15241.  
  15242.    After you have run `configure', and possibly edited the `Makefile',
  15243. type:
  15244.  
  15245.      make
  15246.  
  15247. and shortly thereafter, you should have an executable version of `gawk'.
  15248. That's all there is to it!  (If these steps do not work, please send in
  15249. a bug report; *note Reporting Problems and Bugs: Bugs..)
  15250.  
  15251. 
  15252. File: gawk.info,  Node: Configuration Philosophy,  Prev: Quick Installation,  Up: Unix Installation
  15253.  
  15254. The Configuration Process
  15255. -------------------------
  15256.  
  15257.    (This section is of interest only if you know something about using
  15258. the C language and the Unix operating system.)
  15259.  
  15260.    The source code for `gawk' generally attempts to adhere to formal
  15261. standards wherever possible.  This means that `gawk' uses library
  15262. routines that are specified by the ANSI C standard and by the POSIX
  15263. operating system interface standard.  When using an ANSI C compiler,
  15264. function prototypes are used to help improve the compile-time checking.
  15265.  
  15266.    Many Unix systems do not support all of either the ANSI or the POSIX
  15267. standards.  The `missing' subdirectory in the `gawk' distribution
  15268. contains replacement versions of those subroutines that are most likely
  15269. to be missing.
  15270.  
  15271.    The `config.h' file that is created by the `configure' program
  15272. contains definitions that describe features of the particular operating
  15273. system where you are attempting to compile `gawk'.  The three things
  15274. described by this file are what header files are available, so that
  15275. they can be correctly included, what (supposedly) standard functions
  15276. are actually available in your C libraries, and other miscellaneous
  15277. facts about your variant of Unix.  For example, there may not be an
  15278. `st_blksize' element in the `stat' structure.  In this case
  15279. `HAVE_ST_BLKSIZE' would be undefined.
  15280.  
  15281.    It is possible for your C compiler to lie to `configure'. It may do
  15282. so by not exiting with an error when a library function is not
  15283. available.  To get around this, you can edit the file `custom.h'.  Use
  15284. an `#ifdef' that is appropriate for your system, and either `#define'
  15285. any constants that `configure' should have defined but didn't, or
  15286. `#undef' any constants that `configure' defined and should not have.
  15287. `custom.h' is automatically included by `config.h'.
  15288.  
  15289.    It is also possible that the `configure' program generated by
  15290. `autoconf' will not work on your system in some other fashion.  If you
  15291. do have a problem, the file `configure.in' is the input for `autoconf'.
  15292. You may be able to change this file, and generate a new version of
  15293. `configure' that will work on your system.  *Note Reporting Problems
  15294. and Bugs: Bugs, for information on how to report problems in
  15295. configuring `gawk'.  The same mechanism may be used to send in updates
  15296. to `configure.in' and/or `custom.h'.
  15297.  
  15298. 
  15299. File: gawk.info,  Node: VMS Installation,  Next: PC Installation,  Prev: Unix Installation,  Up: Installation
  15300.  
  15301. How to Compile and Install `gawk' on VMS
  15302. ========================================
  15303.  
  15304.    This section describes how to compile and install `gawk' under VMS.
  15305.  
  15306. * Menu:
  15307.  
  15308. * VMS Compilation::             How to compile `gawk' under VMS.
  15309. * VMS Installation Details::    How to install `gawk' under VMS.
  15310. * VMS Running::                 How to run `gawk' under VMS.
  15311. * VMS POSIX::                   Alternate instructions for VMS POSIX.
  15312.  
  15313. 
  15314. File: gawk.info,  Node: VMS Compilation,  Next: VMS Installation Details,  Prev: VMS Installation,  Up: VMS Installation
  15315.  
  15316. Compiling `gawk' on VMS
  15317. -----------------------
  15318.  
  15319.    To compile `gawk' under VMS, there is a `DCL' command procedure that
  15320. will issue all the necessary `CC' and `LINK' commands, and there is
  15321. also a `Makefile' for use with the `MMS' utility.  From the source
  15322. directory, use either
  15323.  
  15324.      $ @[.VMS]VMSBUILD.COM
  15325.  
  15326. or
  15327.  
  15328.      $ MMS/DESCRIPTION=[.VMS]DESCRIP.MMS GAWK
  15329.  
  15330.    Depending upon which C compiler you are using, follow one of the sets
  15331. of instructions in this table:
  15332.  
  15333. VAX C V3.x
  15334.      Use either `vmsbuild.com' or `descrip.mms' as is.  These use
  15335.      `CC/OPTIMIZE=NOLINE', which is essential for Version 3.0.
  15336.  
  15337. VAX C V2.x
  15338.      You must have Version 2.3 or 2.4; older ones won't work.  Edit
  15339.      either `vmsbuild.com' or `descrip.mms' according to the comments
  15340.      in them.  For `vmsbuild.com', this just entails removing two `!'
  15341.      delimiters.  Also edit `config.h' (which is a copy of file
  15342.      `[.config]vms-conf.h') and comment out or delete the two lines
  15343.      `#define __STDC__ 0' and `#define VAXC_BUILTINS' near the end.
  15344.  
  15345. GNU C
  15346.      Edit `vmsbuild.com' or `descrip.mms'; the changes are different
  15347.      from those for VAX C V2.x, but equally straightforward.  No
  15348.      changes to `config.h' should be needed.
  15349.  
  15350. DEC C
  15351.      Edit `vmsbuild.com' or `descrip.mms' according to their comments.
  15352.      No changes to `config.h' should be needed.
  15353.  
  15354.    `gawk' has been tested under VAX/VMS 5.5-1 using VAX C V3.2, GNU C
  15355. 1.40 and 2.3.  It should work without modifications for VMS V4.6 and up.
  15356.  
  15357. 
  15358. File: gawk.info,  Node: VMS Installation Details,  Next: VMS Running,  Prev: VMS Compilation,  Up: VMS Installation
  15359.  
  15360. Installing `gawk' on VMS
  15361. ------------------------
  15362.  
  15363.    To install `gawk', all you need is a "foreign" command, which is a
  15364. `DCL' symbol whose value begins with a dollar sign. For example:
  15365.  
  15366.      $ GAWK :== $disk1:[gnubin]GAWK
  15367.  
  15368. (Substitute the actual location of `gawk.exe' for `$disk1:[gnubin]'.)
  15369. The symbol should be placed in the `login.com' of any user who wishes
  15370. to run `gawk', so that it will be defined every time the user logs on.
  15371. Alternatively, the symbol may be placed in the system-wide
  15372. `sylogin.com' procedure, which will allow all users to run `gawk'.
  15373.  
  15374.    Optionally, the help entry can be loaded into a VMS help library:
  15375.  
  15376.      $ LIBRARY/HELP SYS$HELP:HELPLIB [.VMS]GAWK.HLP
  15377.  
  15378. (You may want to substitute a site-specific help library rather than
  15379. the standard VMS library `HELPLIB'.)  After loading the help text,
  15380.  
  15381.      $ HELP GAWK
  15382.  
  15383. will provide information about both the `gawk' implementation and the
  15384. `awk' programming language.
  15385.  
  15386.    The logical name `AWK_LIBRARY' can designate a default location for
  15387. `awk' program files.  For the `-f' option, if the specified filename
  15388. has no device or directory path information in it, `gawk' will look in
  15389. the current directory first, then in the directory specified by the
  15390. translation of `AWK_LIBRARY' if the file was not found.  If after
  15391. searching in both directories, the file still is not found, then `gawk'
  15392. appends the suffix `.awk' to the filename and the file search will be
  15393. re-tried.  If `AWK_LIBRARY' is not defined, that portion of the file
  15394. search will fail benignly.
  15395.  
  15396. 
  15397. File: gawk.info,  Node: VMS Running,  Next: VMS POSIX,  Prev: VMS Installation Details,  Up: VMS Installation
  15398.  
  15399. Running `gawk' on VMS
  15400. ---------------------
  15401.  
  15402.    Command line parsing and quoting conventions are significantly
  15403. different on VMS, so examples in this Info file or from other sources
  15404. often need minor changes.  They *are* minor though, and all `awk'
  15405. programs should run correctly.
  15406.  
  15407.    Here are a couple of trivial tests:
  15408.  
  15409.      $ gawk -- "BEGIN {print ""Hello, World!""}"
  15410.      $ gawk -"W" version
  15411.      ! could also be -"W version" or "-W version"
  15412.  
  15413. Note that upper-case and mixed-case text must be quoted.
  15414.  
  15415.    The VMS port of `gawk' includes a `DCL'-style interface in addition
  15416. to the original shell-style interface (see the help entry for details).
  15417. One side-effect of dual command line parsing is that if there is only a
  15418. single parameter (as in the quoted string program above), the command
  15419. becomes ambiguous.  To work around this, the normally optional `--'
  15420. flag is required to force Unix style rather than `DCL' parsing.  If any
  15421. other dash-type options (or multiple parameters such as data files to be
  15422. processed) are present, there is no ambiguity and `--' can be omitted.
  15423.  
  15424.    The default search path when looking for `awk' program files
  15425. specified by the `-f' option is `"SYS$DISK:[],AWK_LIBRARY:"'.  The
  15426. logical name `AWKPATH' can be used to override this default.  The format
  15427. of `AWKPATH' is a comma-separated list of directory specifications.
  15428. When defining it, the value should be quoted so that it retains a single
  15429. translation, and not a multi-translation `RMS' searchlist.
  15430.  
  15431. 
  15432. File: gawk.info,  Node: VMS POSIX,  Prev: VMS Running,  Up: VMS Installation
  15433.  
  15434. Building and Using `gawk' on VMS POSIX
  15435. --------------------------------------
  15436.  
  15437.    Ignore the instructions above, although `vms/gawk.hlp' should still
  15438. be made available in a help library.  Make sure that the `configure'
  15439. script is executable; use `chmod +x' on it if necessary.  Then execute
  15440. the following commands:
  15441.  
  15442.      $ POSIX
  15443.      psx> CC=vms/posix-cc.sh configure
  15444.      psx> CC=c89 make gawk
  15445.  
  15446. The first command will construct files `config.h' and `Makefile' out of
  15447. templates.  The second command will compile and link `gawk'.  Ignore
  15448. the warning `"Could not find lib m in lib list"'; it is harmless,
  15449. caused by the explicit use of `-lm' as a linker option which is not
  15450. needed under VMS POSIX.  Under V1.1 (but not V1.0) a problem with the
  15451. `yacc' skeleton `/etc/yyparse.c' will cause a compiler warning for
  15452. `awktab.c', followed by a linker warning about compilation warnings in
  15453. the resulting object module.  These warnings can be ignored.
  15454.  
  15455.    Once built, `gawk' will work like any other shell utility.  Unlike
  15456. the normal VMS port of `gawk', no special command line manipulation is
  15457. needed in the VMS POSIX environment.
  15458.  
  15459. 
  15460. File: gawk.info,  Node: PC Installation,  Next: Atari Installation,  Prev: VMS Installation,  Up: Installation
  15461.  
  15462. MS-DOS and OS/2 Installation and Compilation
  15463. ============================================
  15464.  
  15465.    If you have received a binary distribution prepared by the DOS
  15466. maintainers, then `gawk' and the necessary support files will appear
  15467. under the `gnu' directory, with executables in `gnu/bin', libraries in
  15468. `gnu/lib/awk', and manual pages under `gnu/man'.  This is designed for
  15469. easy installation to a `/gnu' directory on your drive, but the files
  15470. can be installed anywhere provided `AWKPATH' is set properly.
  15471. Regardless of the installation directory, the first line of `igawk.cmd'
  15472. and `igawk.bat' (in `gnu/bin') may need to be edited.
  15473.  
  15474.    The binary distribution will contain a separate file describing the
  15475. contents. In particular, it may include more than one version of the
  15476. `gawk' executable. OS/2 binary distributions may have a different
  15477. arrangement, but installation is similar.
  15478.  
  15479.    The OS/2 and MS-DOS versions of `gawk' search for program files as
  15480. described in *Note The `AWKPATH' Environment Variable: AWKPATH Variable.
  15481. However, semicolons (rather than colons) separate elements in the
  15482. `AWKPATH' variable. If `AWKPATH' is not set or is empty, then the
  15483. default search path is `".;c:/lib/awk;c:/gnu/lib/awk"'.
  15484.  
  15485.    An `sh'-like shell (as opposed to `command.com' under MS-DOS or
  15486. `cmd.exe' under OS/2) may be useful for `awk' programming.  Ian
  15487. Stewartson has written an excellent shell for MS-DOS and OS/2, and a
  15488. `ksh' clone and GNU Bash are available for OS/2. The file
  15489. `README_d/README.pc' in the `gawk' distribution contains information on
  15490. these shells. Users of Stewartson's shell on DOS should examine its
  15491. documentation on handling of command-lines. In particular, the setting
  15492. for `gawk' in the shell configuration may need to be changed, and the
  15493. `ignoretype' option may also be of interest.
  15494.  
  15495.    `gawk' can be compiled for MS-DOS and OS/2 using the GNU development
  15496. tools from DJ Delorie (DJGPP, MS-DOS-only) or Eberhard Mattes (EMX,
  15497. MS-DOS and OS/2).  Microsoft C can be used to build 16-bit versions for
  15498. MS-DOS and OS/2.  The file `README_d/README.pc' in the `gawk'
  15499. distribution contains additional notes, and `pc/Makefile' contains
  15500. important notes on compilation options.
  15501.  
  15502.    To build `gawk', copy the files in the `pc' directory to the
  15503. directory with the rest of the `gawk' sources. The `Makefile' contains
  15504. a configuration section with comments, and may need to be edited in
  15505. order to work with your `make' utility.
  15506.  
  15507.    The `Makefile' contains a number of targets for building various
  15508. MS-DOS and OS/2 versions. A list of targets will be printed if the
  15509. `make' command is given without a target. As an example, to build `gawk'
  15510. using the DJGPP tools, enter `make djgpp'.
  15511.  
  15512.    Using `make' to run the standard tests and to install `gawk'
  15513. requires additional Unix-like tools, including `sh', `sed', and `cp'.
  15514. In order to run the tests, the `test/*.ok' files may need to be
  15515. converted so that they have the usual DOS-style end-of-line markers.
  15516. Most of the tests will work properly with Stewartson's shell along with
  15517. the companion utilities or appropriate GNU utilities.  However, some
  15518. editing of `test/Makefile' is required. It is recommended that the file
  15519. `pc/Makefile.tst' be copied to `test/Makefile' as a replacement.
  15520. Details can be found in `README_d/README.pc'.
  15521.  
  15522. 
  15523. File: gawk.info,  Node: Atari Installation,  Next: Amiga Installation,  Prev: PC Installation,  Up: Installation
  15524.  
  15525. Installing `gawk' on the Atari ST
  15526. =================================
  15527.  
  15528.    There are no substantial differences when installing `gawk' on
  15529. various Atari models.  Compiled `gawk' executables do not require a
  15530. large amount of memory with most `awk' programs and should run on all
  15531. Motorola processor based models (called further ST, even if that is not
  15532. exactly right).
  15533.  
  15534.    In order to use `gawk', you need to have a shell, either text or
  15535. graphics, that does not map all the characters of a command line to
  15536. upper-case.  Maintaining case distinction in option flags is very
  15537. important (*note Command Line Options: Options.).  These days this is
  15538. the default, and it may only be a problem for some very old machines.
  15539. If your system does not preserve the case of option flags, you will
  15540. need to upgrade your tools.  Support for I/O redirection is necessary
  15541. to make it easy to import `awk' programs from other environments.
  15542. Pipes are nice to have, but not vital.
  15543.  
  15544. * Menu:
  15545.  
  15546. * Atari Compiling::           Compiling `gawk' on Atari
  15547. * Atari Using::               Running `gawk' on Atari
  15548.  
  15549. 
  15550. File: gawk.info,  Node: Atari Compiling,  Next: Atari Using,  Prev: Atari Installation,  Up: Atari Installation
  15551.  
  15552. Compiling `gawk' on the Atari ST
  15553. --------------------------------
  15554.  
  15555.    A proper compilation of `gawk' sources when `sizeof(int)' differs
  15556. from `sizeof(void *)' requires an ANSI C compiler. An initial port was
  15557. done with `gcc'.  You may actually prefer executables where `int's are
  15558. four bytes wide, but the other variant works as well.
  15559.  
  15560.    You may need quite a bit of memory when trying to recompile the
  15561. `gawk' sources, as some source files (`regex.c' in particular) are quite
  15562. big.  If you run out of memory compiling such a file, try reducing the
  15563. optimization level for this particular file; this may help.
  15564.  
  15565.    With a reasonable shell (Bash will do), and in particular if you run
  15566. Linux, MiNT or a similar operating system, you have a pretty good
  15567. chance that the `configure' utility will succeed.  Otherwise sample
  15568. versions of `config.h' and `Makefile.st' are given in the `atari'
  15569. subdirectory and can be edited and copied to the corresponding files in
  15570. the main source directory.  Even if `configure' produced something, it
  15571. might be advisable to compare its results with the sample versions and
  15572. possibly make adjustments.
  15573.  
  15574.    Some `gawk' source code fragments depend on a preprocessor define
  15575. `atarist'.  This basically assumes the TOS environment with `gcc'.
  15576. Modify these sections as appropriate if they are not right for your
  15577. environment.  Also see the remarks about `AWKPATH' and `envsep' in
  15578. *Note Running `gawk' on the Atari ST: Atari Using.
  15579.  
  15580.    As shipped, the sample `config.h' claims that the `system' function
  15581. is missing from the libraries, which is not true, and an alternative
  15582. implementation of this function is provided in `atari/system.c'.
  15583. Depending upon your particular combination of shell and operating
  15584. system, you may wish to change the file to indicate that `system' is
  15585. available.
  15586.  
  15587. 
  15588. File: gawk.info,  Node: Atari Using,  Prev: Atari Compiling,  Up: Atari Installation
  15589.  
  15590. Running `gawk' on the Atari ST
  15591. ------------------------------
  15592.  
  15593.    An executable version of `gawk' should be placed, as usual, anywhere
  15594. in your `PATH' where your shell can find it.
  15595.  
  15596.    While executing, `gawk' creates a number of temporary files.  When
  15597. using `gcc' libraries for TOS, `gawk' looks for either of the
  15598. environment variables `TEMP' or `TMPDIR', in that order.  If either one
  15599. is found, its value is assumed to be a directory for temporary files.
  15600. This directory must exist, and if you can spare the memory, it is a
  15601. good idea to put it on a RAM drive.  If neither `TEMP' nor `TMPDIR' are
  15602. found, then `gawk' uses the current directory for its temporary files.
  15603.  
  15604.    The ST version of `gawk' searches for its program files as described
  15605. in *Note The `AWKPATH' Environment Variable: AWKPATH Variable.  The
  15606. default value for the `AWKPATH' variable is taken from `DEFPATH'
  15607. defined in `Makefile'. The sample `gcc'/TOS `Makefile' for the ST in
  15608. the distribution sets `DEFPATH' to `".,c:\lib\awk,c:\gnu\lib\awk"'.
  15609. The search path can be modified by explicitly setting `AWKPATH' to
  15610. whatever you wish.  Note that colons cannot be used on the ST to
  15611. separate elements in the `AWKPATH' variable, since they have another,
  15612. reserved, meaning.  Instead, you must use a comma to separate elements
  15613. in the path.  When recompiling, the separating character can be
  15614. modified by initializing the `envsep' variable in `atari/gawkmisc.atr'
  15615. to another value.
  15616.  
  15617.    Although `awk' allows great flexibility in doing I/O redirections
  15618. from within a program, this facility should be used with care on the ST
  15619. running under TOS.  In some circumstances the OS routines for file
  15620. handle pool processing lose track of certain events, causing the
  15621. computer to crash, and requiring a reboot.  Often a warm reboot is
  15622. sufficient.  Fortunately, this happens infrequently, and in rather
  15623. esoteric situations.  In particular, avoid having one part of an `awk'
  15624. program using `print' statements explicitly redirected to
  15625. `"/dev/stdout"', while other `print' statements use the default
  15626. standard output, and a calling shell has redirected standard output to
  15627. a file.
  15628.  
  15629.    When `gawk' is compiled with the ST version of `gcc' and its usual
  15630. libraries, it will accept both `/' and `\' as path separators.  While
  15631. this is convenient, it should be remembered that this removes one,
  15632. technically valid, character (`/') from your file names, and that it
  15633. may create problems for external programs, called via the `system'
  15634. function, which may not support this convention.  Whenever it is
  15635. possible that a file created by `gawk' will be used by some other
  15636. program, use only backslashes.  Also remember that in `awk',
  15637. backslashes in strings have to be doubled in order to get literal
  15638. backslashes (*note Escape Sequences::.).
  15639.  
  15640. 
  15641. File: gawk.info,  Node: Amiga Installation,  Next: Bugs,  Prev: Atari Installation,  Up: Installation
  15642.  
  15643. Installing `gawk' on an Amiga
  15644. =============================
  15645.  
  15646.    You can install `gawk' on an Amiga system using a Unix emulation
  15647. environment available via anonymous `ftp' from `wuarchive.wustl.edu' in
  15648. the directory `pub/aminet/dev/gcc'.  This includes a shell based on
  15649. `pdksh'.  The primary component of this environment is a Unix emulation
  15650. library, `ixemul.lib'.
  15651.  
  15652.    A more complete distribution for the Amiga is available on the
  15653. FreshFish CD-ROM from:
  15654.  
  15655.      Amiga Library Services
  15656.      610 North Alma School Road, Suite 18
  15657.      Chandler, AZ  85224  USA
  15658.      Phone: +1-602-491-0048
  15659.      FAX: +1-602-491-0048
  15660.      E-mail:    `orders@amigalib.com'
  15661.  
  15662.    Once you have the distribution, you can configure `gawk' simply by
  15663. running `configure':
  15664.  
  15665.      configure -v m68k-cbm-amigados
  15666.  
  15667.    Then run `make', and you should be all set!  (If these steps do not
  15668. work, please send in a bug report; *note Reporting Problems and Bugs:
  15669. Bugs..)
  15670.  
  15671. 
  15672. File: gawk.info,  Node: Bugs,  Next: Other Versions,  Prev: Amiga Installation,  Up: Installation
  15673.  
  15674. Reporting Problems and Bugs
  15675. ===========================
  15676.  
  15677.    If you have problems with `gawk' or think that you have found a bug,
  15678. please report it to the developers; we cannot promise to do anything
  15679. but we might well want to fix it.
  15680.  
  15681.    Before reporting a bug, make sure you have actually found a real bug.
  15682. Carefully reread the documentation and see if it really says you can do
  15683. what you're trying to do.  If it's not clear whether you should be able
  15684. to do something or not, report that too; it's a bug in the
  15685. documentation!
  15686.  
  15687.    Before reporting a bug or trying to fix it yourself, try to isolate
  15688. it to the smallest possible `awk' program and input data file that
  15689. reproduces the problem.  Then send us the program and data file, some
  15690. idea of what kind of Unix system you're using, and the exact results
  15691. `gawk' gave you.  Also say what you expected to occur; this will help
  15692. us decide whether the problem was really in the documentation.
  15693.  
  15694.    Once you have a precise problem, there are two e-mail addresses you
  15695. can send mail to.
  15696.  
  15697. Internet:
  15698.      `bug-gnu-utils@prep.ai.mit.edu'
  15699.  
  15700. UUCP:
  15701.      `uunet!prep.ai.mit.edu!bug-gnu-utils'
  15702.  
  15703.    Please include the version number of `gawk' you are using.  You can
  15704. get this information with the command `gawk --version'.  You should
  15705. send a carbon copy of your mail to Arnold Robbins, who can be reached
  15706. at `arnold@gnu.ai.mit.edu'.
  15707.  
  15708.    *Important!* Do *not* try to report bugs in `gawk' by posting to the
  15709. Usenet/Internet newsgroup `comp.lang.awk'.  While the `gawk' developers
  15710. do occasionally read this newsgroup, there is no guarantee that we will
  15711. see your posting.  The steps described above are the official,
  15712. recognized ways for reporting bugs.
  15713.  
  15714.    Non-bug suggestions are always welcome as well.  If you have
  15715. questions about things that are unclear in the documentation or are
  15716. just obscure features, ask Arnold Robbins; he will try to help you out,
  15717. although he may not have the time to fix the problem.  You can send him
  15718. electronic mail at the Internet address above.
  15719.  
  15720.    If you find bugs in one of the non-Unix ports of `gawk', please send
  15721. an electronic mail message to the person who maintains that port.  They
  15722. are listed below, and also in the `README' file in the `gawk'
  15723. distribution.  Information in the `README' file should be considered
  15724. authoritative if it conflicts with this Info file.
  15725.  
  15726.    The people maintaining the non-Unix ports of `gawk' are:
  15727.  
  15728. MS-DOS
  15729.      Scott Deifik, `scottd@amgen.com', and Darrel Hankerson,
  15730.      `hankedr@mail.auburn.edu'.
  15731.  
  15732. OS/2
  15733.      Kai Uwe Rommel, `rommel@ars.de'.
  15734.  
  15735. VMS
  15736.      Pat Rankin, `rankin@eql.caltech.edu'.
  15737.  
  15738. Atari ST
  15739.      Michal Jaegermann, `michal@gortel.phys.ualberta.ca'.
  15740.  
  15741. Amiga
  15742.      Fred Fish, `fnf@amigalib.com'.
  15743.  
  15744.    If your bug is also reproducible under Unix, please send copies of
  15745. your report to the general GNU bug list, as well as to Arnold Robbins,
  15746. at the addresses listed above.
  15747.  
  15748. 
  15749. File: gawk.info,  Node: Other Versions,  Prev: Bugs,  Up: Installation
  15750.  
  15751. Other Freely Available `awk' Implementations
  15752. ============================================
  15753.  
  15754.    There are two other freely available `awk' implementations.  This
  15755. section briefly describes where to get them.
  15756.  
  15757. Unix `awk'
  15758.      Brian Kernighan has been able to make his implementation of `awk'
  15759.      freely available.  You can get it via anonymous `ftp' to the host
  15760.      `netlib.att.com'.  Change directory to `/netlib/research'. Use
  15761.      "binary" or "image" mode, and retrieve `awk.bundle.Z'.
  15762.  
  15763.      This is a shell archive that has been compressed with the
  15764.      `compress' utility. It can be uncompressed with either
  15765.      `uncompress' or the GNU `gunzip' utility.
  15766.  
  15767.      This version requires an ANSI C compiler; GCC (the GNU C compiler)
  15768.      works quite nicely.
  15769.  
  15770. `mawk'
  15771.      Michael Brennan has written an independent implementation of `awk',
  15772.      called `mawk'.  It is available under the GPL (*note GNU GENERAL
  15773.      PUBLIC LICENSE: Copying.), just as `gawk' is.
  15774.  
  15775.      You can get it via anonymous `ftp' to the host `oxy.edu'.  Change
  15776.      directory to `/public'. Use "binary" or "image" mode, and retrieve
  15777.      `mawk1.2.1.tar.gz' (or the latest version that is there).
  15778.  
  15779.      `gunzip' may be used to decompress this file. Installation is
  15780.      similar to `gawk''s (*note Compiling and Installing `gawk' on
  15781.      Unix: Unix Installation.).
  15782.  
  15783. 
  15784. File: gawk.info,  Node: Notes,  Next: Glossary,  Prev: Installation,  Up: Top
  15785.  
  15786. Implementation Notes
  15787. ********************
  15788.  
  15789.    This appendix contains information mainly of interest to
  15790. implementors and maintainers of `gawk'.  Everything in it applies
  15791. specifically to `gawk', and not to other implementations.
  15792.  
  15793. * Menu:
  15794.  
  15795. * Compatibility Mode::          How to disable certain `gawk' extensions.
  15796. * Additions::                   Making Additions To `gawk'.
  15797. * Future Extensions::           New features that may be implemented one day.
  15798. * Improvements::                Suggestions for improvements by volunteers.
  15799.  
  15800. 
  15801. File: gawk.info,  Node: Compatibility Mode,  Next: Additions,  Prev: Notes,  Up: Notes
  15802.  
  15803. Downward Compatibility and Debugging
  15804. ====================================
  15805.  
  15806.    *Note Extensions in `gawk' Not in POSIX `awk': POSIX/GNU, for a
  15807. summary of the GNU extensions to the `awk' language and program.  All
  15808. of these features can be turned off by invoking `gawk' with the
  15809. `--traditional' option, or with the `--posix' option.
  15810.  
  15811.    If `gawk' is compiled for debugging with `-DDEBUG', then there is
  15812. one more option available on the command line:
  15813.  
  15814. `-W parsedebug'
  15815. `--parsedebug'
  15816.      Print out the parse stack information as the program is being
  15817.      parsed.
  15818.  
  15819.    This option is intended only for serious `gawk' developers, and not
  15820. for the casual user.  It probably has not even been compiled into your
  15821. version of `gawk', since it slows down execution.
  15822.  
  15823. 
  15824. File: gawk.info,  Node: Additions,  Next: Future Extensions,  Prev: Compatibility Mode,  Up: Notes
  15825.  
  15826. Making Additions to `gawk'
  15827. ==========================
  15828.  
  15829.    If you should find that you wish to enhance `gawk' in a significant
  15830. fashion, you are perfectly free to do so.  That is the point of having
  15831. free software; the source code is available, and you are free to change
  15832. it as you wish (*note GNU GENERAL PUBLIC LICENSE: Copying.).
  15833.  
  15834.    This section discusses the ways you might wish to change `gawk', and
  15835. any considerations you should bear in mind.
  15836.  
  15837. * Menu:
  15838.  
  15839. * Adding Code::             Adding code to the main body of `gawk'.
  15840. * New Ports::               Porting `gawk' to a new operating system.
  15841.  
  15842. 
  15843. File: gawk.info,  Node: Adding Code,  Next: New Ports,  Prev: Additions,  Up: Additions
  15844.  
  15845. Adding New Features
  15846. -------------------
  15847.  
  15848.    You are free to add any new features you like to `gawk'.  However,
  15849. if you want your changes to be incorporated into the `gawk'
  15850. distribution, there are several steps that you need to take in order to
  15851. make it possible for me to include to your changes.
  15852.  
  15853.   1. Get the latest version.  It is much easier for me to integrate
  15854.      changes if they are relative to the most recent distributed
  15855.      version of `gawk'.  If your version of `gawk' is very old, I may
  15856.      not be able to integrate them at all.  *Note Getting the `gawk'
  15857.      Distribution: Getting, for information on getting the latest
  15858.      version of `gawk'.
  15859.  
  15860.   2. See *note : (Version)Top standards, GNU Coding Standards.  This
  15861.      document describes how GNU software should be written. If you
  15862.      haven't read it, please do so, preferably *before* starting to
  15863.      modify `gawk'.  (The `GNU Coding Standards' are available as part
  15864.      of the Autoconf distribution, from the FSF.)
  15865.  
  15866.   3. Use the `gawk' coding style.  The C code for `gawk' follows the
  15867.      instructions in the `GNU Coding Standards', with minor exceptions.
  15868.      The code is formatted using the traditional "K&R" style,
  15869.      particularly as regards the placement of braces and the use of
  15870.      tabs.  In brief, the coding rules for `gawk' are:
  15871.  
  15872.         * Use old style (non-prototype) function headers when defining
  15873.           functions.
  15874.  
  15875.         * Put the name of the function at the beginning of its own line.
  15876.  
  15877.         * Put the return type of the function, even if it is `int', on
  15878.           the line above the line with the name and arguments of the
  15879.           function.
  15880.  
  15881.         * The declarations for the function arguments should not be
  15882.           indented.
  15883.  
  15884.         * Put spaces around parentheses used in control structures
  15885.           (`if', `while', `for', `do', `switch' and `return').
  15886.  
  15887.         * Do not put spaces in front of parentheses used in function
  15888.           calls.
  15889.  
  15890.         * Put spaces around all C operators, and after commas in
  15891.           function calls.
  15892.  
  15893.         * Do not use the comma operator to produce multiple
  15894.           side-effects, except in `for' loop initialization and
  15895.           increment parts, and in macro bodies.
  15896.  
  15897.         * Use real tabs for indenting, not spaces.
  15898.  
  15899.         * Use the "K&R" brace layout style.
  15900.  
  15901.         * Use comparisons against `NULL' and `'\0'' in the conditions of
  15902.           `if', `while' and `for' statements, and in the `case's of
  15903.           `switch' statements, instead of just the plain pointer or
  15904.           character value.
  15905.  
  15906.         * Use the `TRUE', `FALSE', and `NULL' symbolic constants, and
  15907.           the character constant `'\0'' where appropriate, instead of
  15908.           `1' and `0'.
  15909.  
  15910.         * Provide one-line descriptive comments for each function.
  15911.  
  15912.         * Do not use `#elif'. Many older Unix C compilers cannot handle
  15913.           it.
  15914.  
  15915.      If I have to reformat your code to follow the coding style used in
  15916.      `gawk', I may not bother.
  15917.  
  15918.   4. Be prepared to sign the appropriate paperwork.  In order for the
  15919.      FSF to distribute your changes, you must either place those
  15920.      changes in the public domain, and submit a signed statement to that
  15921.      effect, or assign the copyright in your changes to the FSF.  Both
  15922.      of these actions are easy to do, and *many* people have done so
  15923.      already. If you have questions, please contact me (*note Reporting
  15924.      Problems and Bugs: Bugs.), or `gnu@prep.ai.mit.edu'.
  15925.  
  15926.   5. Update the documentation.  Along with your new code, please supply
  15927.      new sections and or chapters for this Info file.  If at all
  15928.      possible, please use real Texinfo, instead of just supplying
  15929.      unformatted ASCII text (although even that is better than no
  15930.      documentation at all).  Conventions to be followed in `AWK
  15931.      Language Programming' are provided after the `@bye' at the end of
  15932.      the Texinfo source file.  If possible, please update the man page
  15933.      as well.
  15934.  
  15935.      You will also have to sign paperwork for your documentation
  15936.      changes.
  15937.  
  15938.   6. Submit changes as context diffs or unified diffs.  Use `diff -c -r
  15939.      -N' or `diff -u -r -N' to compare the original `gawk' source tree
  15940.      with your version.  (I find context diffs to be more readable, but
  15941.      unified diffs are more compact.) I recommend using the GNU version
  15942.      of `diff'.  Send the output produced by either run of `diff' to me
  15943.      when you submit your changes.  *Note Reporting Problems and Bugs:
  15944.      Bugs, for the electronic mail information.
  15945.  
  15946.      Using this format makes it easy for me to apply your changes to the
  15947.      master version of the `gawk' source code (using `patch').  If I
  15948.      have to apply the changes manually, using a text editor, I may not
  15949.      do so, particularly if there are lots of changes.
  15950.  
  15951.    Although this sounds like a lot of work, please remember that while
  15952. you may write the new code, I have to maintain it and support it, and
  15953. if it isn't possible for me to do that with a minimum of extra work,
  15954. then I probably will not.
  15955.  
  15956. 
  15957. File: gawk.info,  Node: New Ports,  Prev: Adding Code,  Up: Additions
  15958.  
  15959. Porting `gawk' to a New Operating System
  15960. ----------------------------------------
  15961.  
  15962.    If you wish to port `gawk' to a new operating system, there are
  15963. several steps to follow.
  15964.  
  15965.   1. Follow the guidelines in *Note Adding New Features: Adding Code,
  15966.      concerning coding style, submission of diffs, and so on.
  15967.  
  15968.   2. When doing a port, bear in mind that your code must co-exist
  15969.      peacefully with the rest of `gawk', and the other ports. Avoid
  15970.      gratuitous changes to the system-independent parts of the code. If
  15971.      at all possible, avoid sprinkling `#ifdef's just for your port
  15972.      throughout the code.
  15973.  
  15974.      If the changes needed for a particular system affect too much of
  15975.      the code, I probably will not accept them.  In such a case, you
  15976.      will, of course, be able to distribute your changes on your own,
  15977.      as long as you comply with the GPL (*note GNU GENERAL PUBLIC
  15978.      LICENSE: Copying.).
  15979.  
  15980.   3. A number of the files that come with `gawk' are maintained by other
  15981.      people at the Free Software Foundation.  Thus, you should not
  15982.      change them unless it is for a very good reason. I.e. changes are
  15983.      not out of the question, but changes to these files will be
  15984.      scrutinized extra carefully.  The files are `alloca.c',
  15985.      `getopt.h', `getopt.c', `getopt1.c', `regex.h', `regex.c', `dfa.h',
  15986.      `dfa.c', `install-sh', and `mkinstalldirs'.
  15987.  
  15988.   4. Be willing to continue to maintain the port.  Non-Unix operating
  15989.      systems are supported by volunteers who maintain the code needed
  15990.      to compile and run `gawk' on their systems. If no-one volunteers
  15991.      to maintain a port, that port becomes unsupported, and it may be
  15992.      necessary to remove it from the distribution.
  15993.  
  15994.   5. Supply an appropriate `gawkmisc.???' file.  Each port has its own
  15995.      `gawkmisc.???' that implements certain operating system specific
  15996.      functions. This is cleaner than a plethora of `#ifdef's scattered
  15997.      throughout the code.  The `gawkmisc.c' in the main source
  15998.      directory includes the appropriate `gawkmisc.???' file from each
  15999.      subdirectory.  Be sure to update it as well.
  16000.  
  16001.      Each port's `gawkmisc.???' file has a suffix reminiscent of the
  16002.      machine or operating system for the port. For example,
  16003.      `pc/gawkmisc.pc' and `vms/gawkmisc.vms'. The use of separate
  16004.      suffixes, instead of plain `gawkmisc.c', makes it possible to move
  16005.      files from a port's subdirectory into the main subdirectory,
  16006.      without accidentally destroying the real `gawkmisc.c' file.
  16007.      (Currently, this is only an issue for the MS-DOS and OS/2 ports.)
  16008.  
  16009.   6. Supply a `Makefile' and any other C source and header files that
  16010.      are necessary for your operating system.  All your code should be
  16011.      in a separate subdirectory, with a name that is the same as, or
  16012.      reminiscent of, either your operating system or the computer
  16013.      system.  If possible, try to structure things so that it is not
  16014.      necessary to move files out of the subdirectory into the main
  16015.      source directory.  If that is not possible, then be sure to avoid
  16016.      using names for your files that duplicate the names of files in
  16017.      the main source directory.
  16018.  
  16019.   7. Update the documentation.  Please write a section (or sections)
  16020.      for this Info file describing the installation and compilation
  16021.      steps needed to install and/or compile `gawk' for your system.
  16022.  
  16023.   8. Be prepared to sign the appropriate paperwork.  In order for the
  16024.      FSF to distribute your code, you must either place your code in
  16025.      the public domain, and submit a signed statement to that effect,
  16026.      or assign the copyright in your code to the FSF.  Both of these
  16027.      actions are easy to do, and *many* people have done so already. If
  16028.      you have questions, please contact me, or `gnu@prep.ai.mit.edu'.
  16029.  
  16030.    Following these steps will make it much easier to integrate your
  16031. changes into `gawk', and have them co-exist happily with the code for
  16032. other operating systems that is already there.
  16033.  
  16034.    In the code that you supply, and that you maintain, feel free to use
  16035. a coding style and brace layout that suits your taste.
  16036.  
  16037. 
  16038. File: gawk.info,  Node: Future Extensions,  Next: Improvements,  Prev: Additions,  Up: Notes
  16039.  
  16040. Probable Future Extensions
  16041. ==========================
  16042.  
  16043.      AWK is a language similar to PERL, only considerably more elegant.
  16044.      Arnold Robbins
  16045.      
  16046.      Hey!
  16047.      Larry Wall
  16048.  
  16049.    This section briefly lists extensions and possible improvements that
  16050. indicate the directions we are currently considering for `gawk'.  The
  16051. file `FUTURES' in the `gawk' distributions lists these extensions as
  16052. well.
  16053.  
  16054.    This is a list of probable future changes that will be usable by the
  16055. `awk' language programmer.
  16056.  
  16057. Localization
  16058.      The GNU project is starting to support multiple languages.  It
  16059.      will at least be possible to make `gawk' print its warnings and
  16060.      error messages in languages other than English.  It may be
  16061.      possible for `awk' programs to also use the multiple language
  16062.      facilities, separate from `gawk' itself.
  16063.  
  16064. Databases
  16065.      It may be possible to map a GDBM/NDBM/SDBM file into an `awk'
  16066.      array.
  16067.  
  16068. A `PROCINFO' Array
  16069.      The special files that provide process-related information (*note
  16070.      Special File Names in `gawk': Special Files.) may be superseded by
  16071.      a `PROCINFO' array that would provide the same information, in an
  16072.      easier to access fashion.
  16073.  
  16074. More `lint' warnings
  16075.      There are more things that could be checked for portability.
  16076.  
  16077. Control of subprocess environment
  16078.      Changes made in `gawk' to the array `ENVIRON' may be propagated to
  16079.      subprocesses run by `gawk'.
  16080.  
  16081.    This is a list of probable improvements that will make `gawk'
  16082. perform better.
  16083.  
  16084. An Improved Version of `dfa'
  16085.      The `dfa' pattern matcher from GNU `grep' has some problems.
  16086.      Either a new version or a fixed one will deal with some important
  16087.      regexp matching issues.
  16088.  
  16089. Use of `mmap'
  16090.      On systems that support the `mmap' system call, its use would
  16091.      provide much faster file input, and considerably simplified input
  16092.      buffer management.
  16093.  
  16094. Use of GNU `malloc'
  16095.      The GNU version of `malloc' could potentially speed up `gawk',
  16096.      since it relies heavily on the use of dynamic memory allocation.
  16097.  
  16098. Use of the `rx' regexp library
  16099.      The `rx' regular expression library could potentially speed up all
  16100.      regexp operations that require knowing the exact location of
  16101.      matches.  This includes record termination, field and array
  16102.      splitting, and the `sub', `gsub', `gensub' and `match' functions.
  16103.  
  16104. 
  16105. File: gawk.info,  Node: Improvements,  Prev: Future Extensions,  Up: Notes
  16106.  
  16107. Suggestions for Improvements
  16108. ============================
  16109.  
  16110.    Here are some projects that would-be `gawk' hackers might like to
  16111. take on.  They vary in size from a few days to a few weeks of
  16112. programming, depending on which one you choose and how fast a
  16113. programmer you are.  Please send any improvements you write to the
  16114. maintainers at the GNU project.  *Note Adding New Features: Adding Code,
  16115. for guidelines to follow when adding new features to `gawk'.  *Note
  16116. Reporting Problems and Bugs: Bugs, for information on contacting the
  16117. maintainers.
  16118.  
  16119.   1. Compilation of `awk' programs: `gawk' uses a Bison (YACC-like)
  16120.      parser to convert the script given it into a syntax tree; the
  16121.      syntax tree is then executed by a simple recursive evaluator.
  16122.      This method incurs a lot of overhead, since the recursive
  16123.      evaluator performs many procedure calls to do even the simplest
  16124.      things.
  16125.  
  16126.      It should be possible for `gawk' to convert the script's parse tree
  16127.      into a C program which the user would then compile, using the
  16128.      normal C compiler and a special `gawk' library to provide all the
  16129.      needed functions (regexps, fields, associative arrays, type
  16130.      coercion, and so on).
  16131.  
  16132.      An easier possibility might be for an intermediate phase of `awk'
  16133.      to convert the parse tree into a linear byte code form like the
  16134.      one used in GNU Emacs Lisp.  The recursive evaluator would then be
  16135.      replaced by a straight line byte code interpreter that would be
  16136.      intermediate in speed between running a compiled program and doing
  16137.      what `gawk' does now.
  16138.  
  16139.   2. The programs in the test suite could use documenting in this
  16140.      Info file.
  16141.  
  16142.   3. See the `FUTURES' file for more ideas.  Contact us if you would
  16143.      seriously like to tackle any of the items listed there.
  16144.  
  16145. 
  16146. File: gawk.info,  Node: Glossary,  Next: Copying,  Prev: Notes,  Up: Top
  16147.  
  16148. Glossary
  16149. ********
  16150.  
  16151. Action
  16152.      A series of `awk' statements attached to a rule.  If the rule's
  16153.      pattern matches an input record, `awk' executes the rule's action.
  16154.      Actions are always enclosed in curly braces.  *Note Overview of
  16155.      Actions: Action Overview.
  16156.  
  16157. Amazing `awk' Assembler
  16158.      Henry Spencer at the University of Toronto wrote a retargetable
  16159.      assembler completely as `awk' scripts.  It is thousands of lines
  16160.      long, including machine descriptions for several eight-bit
  16161.      microcomputers.  It is a good example of a program that would have
  16162.      been better written in another language.
  16163.  
  16164. Amazingly Workable Formatter (`awf')
  16165.      Henry Spencer at the University of Toronto wrote a formatter that
  16166.      accepts a large subset of the `nroff -ms' and `nroff -man'
  16167.      formatting commands, using `awk' and `sh'.
  16168.  
  16169. ANSI
  16170.      The American National Standards Institute.  This organization
  16171.      produces many standards, among them the standards for the C and
  16172.      C++ programming languages.
  16173.  
  16174. Assignment
  16175.      An `awk' expression that changes the value of some `awk' variable
  16176.      or data object.  An object that you can assign to is called an
  16177.      "lvalue".  The assigned values are called "rvalues".  *Note
  16178.      Assignment Expressions: Assignment Ops.
  16179.  
  16180. `awk' Language
  16181.      The language in which `awk' programs are written.
  16182.  
  16183. `awk' Program
  16184.      An `awk' program consists of a series of "patterns" and "actions",
  16185.      collectively known as "rules".  For each input record given to the
  16186.      program, the program's rules are all processed in turn.  `awk'
  16187.      programs may also contain function definitions.
  16188.  
  16189. `awk' Script
  16190.      Another name for an `awk' program.
  16191.  
  16192. Bash
  16193.      The GNU version of the standard shell (the Bourne-Again shell).
  16194.      See "Bourne Shell."
  16195.  
  16196. BBS
  16197.      See "Bulletin Board System."
  16198.  
  16199. Boolean Expression
  16200.      Named after the English mathematician Boole. See "Logical
  16201.      Expression."
  16202.  
  16203. Bourne Shell
  16204.      The standard shell (`/bin/sh') on Unix and Unix-like systems,
  16205.      originally written by Steven R. Bourne.  Many shells (Bash, `ksh',
  16206.      `pdksh', `zsh') are generally upwardly compatible with the Bourne
  16207.      shell.
  16208.  
  16209. Built-in Function
  16210.      The `awk' language provides built-in functions that perform various
  16211.      numerical, time stamp related, and string computations.  Examples
  16212.      are `sqrt' (for the square root of a number) and `substr' (for a
  16213.      substring of a string).  *Note Built-in Functions: Built-in.
  16214.  
  16215. Built-in Variable
  16216.      `ARGC', `ARGIND', `ARGV', `CONVFMT', `ENVIRON', `ERRNO',
  16217.      `FIELDWIDTHS', `FILENAME', `FNR', `FS', `IGNORECASE', `NF', `NR',
  16218.      `OFMT', `OFS', `ORS', `RLENGTH', `RSTART', `RS', `RT', and
  16219.      `SUBSEP', are the variables that have special meaning to `awk'.
  16220.      Changing some of them affects `awk''s running environment.
  16221.      Several of these variables are specific to `gawk'.  *Note Built-in
  16222.      Variables::.
  16223.  
  16224. Braces
  16225.      See "Curly Braces."
  16226.  
  16227. Bulletin Board System
  16228.      A computer system allowing users to log in and read and/or leave
  16229.      messages for other users of the system, much like leaving paper
  16230.      notes on a bulletin board.
  16231.  
  16232. C
  16233.      The system programming language that most GNU software is written
  16234.      in.  The `awk' programming language has C-like syntax, and this
  16235.      Info file points out similarities between `awk' and C when
  16236.      appropriate.
  16237.  
  16238. Character Set
  16239.      The set of numeric codes used by a computer system to represent the
  16240.      characters (letters, numbers, punctuation, etc.) of a particular
  16241.      country or place. The most common character set in use today is
  16242.      ASCII (American Standard Code for Information Interchange).  Many
  16243.      European countries use an extension of ASCII known as ISO-8859-1
  16244.      (ISO Latin-1).
  16245.  
  16246. CHEM
  16247.      A preprocessor for `pic' that reads descriptions of molecules and
  16248.      produces `pic' input for drawing them.  It was written in `awk' by
  16249.      Brian Kernighan and Jon Bentley, and is available from
  16250.      `netlib@research.att.com'.
  16251.  
  16252. Compound Statement
  16253.      A series of `awk' statements, enclosed in curly braces.  Compound
  16254.      statements may be nested.  *Note Control Statements in Actions:
  16255.      Statements.
  16256.  
  16257. Concatenation
  16258.      Concatenating two strings means sticking them together, one after
  16259.      another, giving a new string.  For example, the string `foo'
  16260.      concatenated with the string `bar' gives the string `foobar'.
  16261.      *Note String Concatenation: Concatenation.
  16262.  
  16263. Conditional Expression
  16264.      An expression using the `?:' ternary operator, such as `EXPR1 ?
  16265.      EXPR2 : EXPR3'.  The expression EXPR1 is evaluated; if the result
  16266.      is true, the value of the whole expression is the value of EXPR2,
  16267.      otherwise the value is EXPR3.  In either case, only one of EXPR2
  16268.      and EXPR3 is evaluated.  *Note Conditional Expressions:
  16269.      Conditional Exp.
  16270.  
  16271. Comparison Expression
  16272.      A relation that is either true or false, such as `(a < b)'.
  16273.      Comparison expressions are used in `if', `while', `do', and `for'
  16274.      statements, and in patterns to select which input records to
  16275.      process.  *Note Variable Typing and Comparison Expressions: Typing
  16276.      and Comparison.
  16277.  
  16278. Curly Braces
  16279.      The characters `{' and `}'.  Curly braces are used in `awk' for
  16280.      delimiting actions, compound statements, and function bodies.
  16281.  
  16282. Dark Corner
  16283.      An area in the language where specifications often were (or still
  16284.      are) not clear, leading to unexpected or undesirable behavior.
  16285.      Such areas are marked in this Info file with "(d.c.)" in the text,
  16286.      and are indexed under the heading "dark corner."
  16287.  
  16288. Data Objects
  16289.      These are numbers and strings of characters.  Numbers are
  16290.      converted into strings and vice versa, as needed.  *Note
  16291.      Conversion of Strings and Numbers: Conversion.
  16292.  
  16293. Double Precision
  16294.      An internal representation of numbers that can have fractional
  16295.      parts.  Double precision numbers keep track of more digits than do
  16296.      single precision numbers, but operations on them are more
  16297.      expensive.  This is the way `awk' stores numeric values.  It is
  16298.      the C type `double'.
  16299.  
  16300. Dynamic Regular Expression
  16301.      A dynamic regular expression is a regular expression written as an
  16302.      ordinary expression.  It could be a string constant, such as
  16303.      `"foo"', but it may also be an expression whose value can vary.
  16304.      *Note Using Dynamic Regexps: Computed Regexps.
  16305.  
  16306. Environment
  16307.      A collection of strings, of the form NAME`='VAL, that each program
  16308.      has available to it. Users generally place values into the
  16309.      environment in order to provide information to various programs.
  16310.      Typical examples are the environment variables `HOME' and `PATH'.
  16311.  
  16312. Empty String
  16313.      See "Null String."
  16314.  
  16315. Escape Sequences
  16316.      A special sequence of characters used for describing non-printing
  16317.      characters, such as `\n' for newline, or `\033' for the ASCII ESC
  16318.      (escape) character.  *Note Escape Sequences::.
  16319.  
  16320. Field
  16321.      When `awk' reads an input record, it splits the record into pieces
  16322.      separated by whitespace (or by a separator regexp which you can
  16323.      change by setting the built-in variable `FS').  Such pieces are
  16324.      called fields.  If the pieces are of fixed length, you can use the
  16325.      built-in variable `FIELDWIDTHS' to describe their lengths.  *Note
  16326.      Specifying How Fields are Separated: Field Separators, and also see
  16327.      *Note Reading Fixed-width Data: Constant Size.
  16328.  
  16329. Floating Point Number
  16330.      Often referred to in mathematical terms as a "rational" number,
  16331.      this is just a number that can have a fractional part.  See
  16332.      "Double Precision" and "Single Precision."
  16333.  
  16334. Format
  16335.      Format strings are used to control the appearance of output in the
  16336.      `printf' statement.  Also, data conversions from numbers to strings
  16337.      are controlled by the format string contained in the built-in
  16338.      variable `CONVFMT'.  *Note Format-Control Letters: Control Letters.
  16339.  
  16340. Function
  16341.      A specialized group of statements used to encapsulate general or
  16342.      program-specific tasks.  `awk' has a number of built-in functions,
  16343.      and also allows you to define your own.  *Note Built-in Functions:
  16344.      Built-in, and *Note User-defined Functions: User-defined.
  16345.  
  16346. FSF
  16347.      See "Free Software Foundation."
  16348.  
  16349. Free Software Foundation
  16350.      A non-profit organization dedicated to the production and
  16351.      distribution of freely distributable software.  It was founded by
  16352.      Richard M. Stallman, the author of the original Emacs editor.  GNU
  16353.      Emacs is the most widely used version of Emacs today.
  16354.  
  16355. `gawk'
  16356.      The GNU implementation of `awk'.
  16357.  
  16358. General Public License
  16359.      This document describes the terms under which `gawk' and its source
  16360.      code may be distributed. (*note GNU GENERAL PUBLIC LICENSE:
  16361.      Copying.)
  16362.  
  16363. GNU
  16364.      "GNU's not Unix".  An on-going project of the Free Software
  16365.      Foundation to create a complete, freely distributable,
  16366.      POSIX-compliant computing environment.
  16367.  
  16368. GPL
  16369.      See "General Public License."
  16370.  
  16371. Hexadecimal
  16372.      Base 16 notation, where the digits are `0'-`9' and `A'-`F', with
  16373.      `A' representing 10, `B' representing 11, and so on up to `F' for
  16374.      15.  Hexadecimal numbers are written in C using a leading `0x', to
  16375.      indicate their base.  Thus, `0x12' is 18 (one times 16 plus 2).
  16376.  
  16377. I/O
  16378.      Abbreviation for "Input/Output," the act of moving data into and/or
  16379.      out of a running program.
  16380.  
  16381. Input Record
  16382.      A single chunk of data read in by `awk'.  Usually, an `awk' input
  16383.      record consists of one line of text.  *Note How Input is Split
  16384.      into Records: Records.
  16385.  
  16386. Integer
  16387.      A whole number, i.e. a number that does not have a fractional part.
  16388.  
  16389. Keyword
  16390.      In the `awk' language, a keyword is a word that has special
  16391.      meaning.  Keywords are reserved and may not be used as variable
  16392.      names.
  16393.  
  16394.      `gawk''s keywords are: `BEGIN', `END', `if', `else', `while',
  16395.      `do...while', `for', `for...in', `break', `continue', `delete',
  16396.      `next', `nextfile', `function', `func', and `exit'.
  16397.  
  16398. Logical Expression
  16399.      An expression using the operators for logic, AND, OR, and NOT,
  16400.      written `&&', `||', and `!' in `awk'. Often called Boolean
  16401.      expressions, after the mathematician who pioneered this kind of
  16402.      mathematical logic.
  16403.  
  16404. Lvalue
  16405.      An expression that can appear on the left side of an assignment
  16406.      operator.  In most languages, lvalues can be variables or array
  16407.      elements.  In `awk', a field designator can also be used as an
  16408.      lvalue.
  16409.  
  16410. Null String
  16411.      A string with no characters in it.  It is represented explicitly in
  16412.      `awk' programs by placing two double-quote characters next to each
  16413.      other (`""').  It can appear in input data by having two successive
  16414.      occurrences of the field separator appear next to each other.
  16415.  
  16416. Number
  16417.      A numeric valued data object.  The `gawk' implementation uses
  16418.      double precision floating point to represent numbers.  Very old
  16419.      `awk' implementations use single precision floating point.
  16420.  
  16421. Octal
  16422.      Base-eight notation, where the digits are `0'-`7'.  Octal numbers
  16423.      are written in C using a leading `0', to indicate their base.
  16424.      Thus, `013' is 11 (one times 8 plus 3).
  16425.  
  16426. Pattern
  16427.      Patterns tell `awk' which input records are interesting to which
  16428.      rules.
  16429.  
  16430.      A pattern is an arbitrary conditional expression against which
  16431.      input is tested.  If the condition is satisfied, the pattern is
  16432.      said to "match" the input record.  A typical pattern might compare
  16433.      the input record against a regular expression.  *Note Pattern
  16434.      Elements: Pattern Overview.
  16435.  
  16436. POSIX
  16437.      The name for a series of standards being developed by the IEEE
  16438.      that specify a Portable Operating System interface.  The "IX"
  16439.      denotes the Unix heritage of these standards.  The main standard
  16440.      of interest for `awk' users is `IEEE Standard for Information
  16441.      Technology, Standard 1003.2-1992, Portable Operating System
  16442.      Interface (POSIX) Part 2: Shell and Utilities'.  Informally, this
  16443.      standard is often referred to as simply "P1003.2."
  16444.  
  16445. Private
  16446.      Variables and/or functions that are meant for use exclusively by
  16447.      library functions, and not for the main `awk' program. Special
  16448.      care must be taken when naming such variables and functions.
  16449.      *Note Naming Library Function Global Variables: Library Names.
  16450.  
  16451. Range (of input lines)
  16452.      A sequence of consecutive lines from the input file.  A pattern
  16453.      can specify ranges of input lines for `awk' to process, or it can
  16454.      specify single lines.  *Note Pattern Elements: Pattern Overview.
  16455.  
  16456. Recursion
  16457.      When a function calls itself, either directly or indirectly.  If
  16458.      this isn't clear, refer to the entry for "recursion."
  16459.  
  16460. Redirection
  16461.      Redirection means performing input from other than the standard
  16462.      input stream, or output to other than the standard output stream.
  16463.  
  16464.      You can redirect the output of the `print' and `printf' statements
  16465.      to a file or a system command, using the `>', `>>', and `|'
  16466.      operators.  You can redirect input to the `getline' statement using
  16467.      the `<' and `|' operators.  *Note Redirecting Output of `print'
  16468.      and `printf': Redirection, and *Note Explicit Input with
  16469.      `getline': Getline.
  16470.  
  16471. Regexp
  16472.      Short for "regular expression".  A regexp is a pattern that
  16473.      denotes a set of strings, possibly an infinite set.  For example,
  16474.      the regexp `R.*xp' matches any string starting with the letter `R'
  16475.      and ending with the letters `xp'.  In `awk', regexps are used in
  16476.      patterns and in conditional expressions.  Regexps may contain
  16477.      escape sequences.  *Note Regular Expressions: Regexp.
  16478.  
  16479. Regular Expression
  16480.      See "regexp."
  16481.  
  16482. Regular Expression Constant
  16483.      A regular expression constant is a regular expression written
  16484.      within slashes, such as `/foo/'.  This regular expression is chosen
  16485.      when you write the `awk' program, and cannot be changed doing its
  16486.      execution.  *Note How to Use Regular Expressions: Regexp Usage.
  16487.  
  16488. Rule
  16489.      A segment of an `awk' program that specifies how to process single
  16490.      input records.  A rule consists of a "pattern" and an "action".
  16491.      `awk' reads an input record; then, for each rule, if the input
  16492.      record satisfies the rule's pattern, `awk' executes the rule's
  16493.      action.  Otherwise, the rule does nothing for that input record.
  16494.  
  16495. Rvalue
  16496.      A value that can appear on the right side of an assignment
  16497.      operator.  In `awk', essentially every expression has a value.
  16498.      These values are rvalues.
  16499.  
  16500. `sed'
  16501.      See "Stream Editor."
  16502.  
  16503. Short-Circuit
  16504.      The nature of the `awk' logical operators `&&' and `||'.  If the
  16505.      value of the entire expression can be deduced from evaluating just
  16506.      the left-hand side of these operators, the right-hand side will not
  16507.      be evaluated (*note Boolean Expressions: Boolean Ops.).
  16508.  
  16509. Side Effect
  16510.      A side effect occurs when an expression has an effect aside from
  16511.      merely producing a value.  Assignment expressions, increment and
  16512.      decrement expressions and function calls have side effects.  *Note
  16513.      Assignment Expressions: Assignment Ops.
  16514.  
  16515. Single Precision
  16516.      An internal representation of numbers that can have fractional
  16517.      parts.  Single precision numbers keep track of fewer digits than
  16518.      do double precision numbers, but operations on them are less
  16519.      expensive in terms of CPU time.  This is the type used by some
  16520.      very old versions of `awk' to store numeric values.  It is the C
  16521.      type `float'.
  16522.  
  16523. Space
  16524.      The character generated by hitting the space bar on the keyboard.
  16525.  
  16526. Special File
  16527.      A file name interpreted internally by `gawk', instead of being
  16528.      handed directly to the underlying operating system.  For example,
  16529.      `/dev/stderr'.  *Note Special File Names in `gawk': Special Files.
  16530.  
  16531. Stream Editor
  16532.      A program that reads records from an input stream and processes
  16533.      them one or more at a time.  This is in contrast with batch
  16534.      programs, which may expect to read their input files in entirety
  16535.      before starting to do anything, and with interactive programs,
  16536.      which require input from the user.
  16537.  
  16538. String
  16539.      A datum consisting of a sequence of characters, such as `I am a
  16540.      string'.  Constant strings are written with double-quotes in the
  16541.      `awk' language, and may contain escape sequences.  *Note Escape
  16542.      Sequences::.
  16543.  
  16544. Tab
  16545.      The character generated by hitting the `TAB' key on the keyboard.
  16546.      It usually expands to up to eight spaces upon output.
  16547.  
  16548. Unix
  16549.      A computer operating system originally developed in the early
  16550.      1970's at AT&T Bell Laboratories.  It initially became popular in
  16551.      universities around the world, and later moved into commercial
  16552.      evnironments as a software development system and network server
  16553.      system. There are many commercial versions of Unix, as well as
  16554.      several work-alike systems whose source code is freely available
  16555.      (such as Linux, NetBSD, and FreeBSD).
  16556.  
  16557. Whitespace
  16558.      A sequence of space or tab characters occurring inside an input
  16559.      record or a string.
  16560.  
  16561. 
  16562. File: gawk.info,  Node: Copying,  Next: Index,  Prev: Glossary,  Up: Top
  16563.  
  16564. GNU GENERAL PUBLIC LICENSE
  16565. **************************
  16566.  
  16567.                          Version 2, June 1991
  16568.  
  16569.      Copyright (C) 1989, 1991 Free Software Foundation, Inc.
  16570.      59 Temple Place --- Suite 330, Boston, MA 02111-1307, USA
  16571.      
  16572.      Everyone is permitted to copy and distribute verbatim copies
  16573.      of this license document, but changing it is not allowed.
  16574.  
  16575. Preamble
  16576. ========
  16577.  
  16578.    The licenses for most software are designed to take away your
  16579. freedom to share and change it.  By contrast, the GNU General Public
  16580. License is intended to guarantee your freedom to share and change free
  16581. software--to make sure the software is free for all its users.  This
  16582. General Public License applies to most of the Free Software
  16583. Foundation's software and to any other program whose authors commit to
  16584. using it.  (Some other Free Software Foundation software is covered by
  16585. the GNU Library General Public License instead.)  You can apply it to
  16586. your programs, too.
  16587.  
  16588.    When we speak of free software, we are referring to freedom, not
  16589. price.  Our General Public Licenses are designed to make sure that you
  16590. have the freedom to distribute copies of free software (and charge for
  16591. this service if you wish), that you receive source code or can get it
  16592. if you want it, that you can change the software or use pieces of it in
  16593. new free programs; and that you know you can do these things.
  16594.  
  16595.    To protect your rights, we need to make restrictions that forbid
  16596. anyone to deny you these rights or to ask you to surrender the rights.
  16597. These restrictions translate to certain responsibilities for you if you
  16598. distribute copies of the software, or if you modify it.
  16599.  
  16600.    For example, if you distribute copies of such a program, whether
  16601. gratis or for a fee, you must give the recipients all the rights that
  16602. you have.  You must make sure that they, too, receive or can get the
  16603. source code.  And you must show them these terms so they know their
  16604. rights.
  16605.  
  16606.    We protect your rights with two steps: (1) copyright the software,
  16607. and (2) offer you this license which gives you legal permission to copy,
  16608. distribute and/or modify the software.
  16609.  
  16610.    Also, for each author's protection and ours, we want to make certain
  16611. that everyone understands that there is no warranty for this free
  16612. software.  If the software is modified by someone else and passed on, we
  16613. want its recipients to know that what they have is not the original, so
  16614. that any problems introduced by others will not reflect on the original
  16615. authors' reputations.
  16616.  
  16617.    Finally, any free program is threatened constantly by software
  16618. patents.  We wish to avoid the danger that redistributors of a free
  16619. program will individually obtain patent licenses, in effect making the
  16620. program proprietary.  To prevent this, we have made it clear that any
  16621. patent must be licensed for everyone's free use or not licensed at all.
  16622.  
  16623.    The precise terms and conditions for copying, distribution and
  16624. modification follow.
  16625.  
  16626.     TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
  16627.  
  16628.   0. This License applies to any program or other work which contains a
  16629.      notice placed by the copyright holder saying it may be distributed
  16630.      under the terms of this General Public License.  The "Program",
  16631.      below, refers to any such program or work, and a "work based on
  16632.      the Program" means either the Program or any derivative work under
  16633.      copyright law: that is to say, a work containing the Program or a
  16634.      portion of it, either verbatim or with modifications and/or
  16635.      translated into another language.  (Hereinafter, translation is
  16636.      included without limitation in the term "modification".)  Each
  16637.      licensee is addressed as "you".
  16638.  
  16639.      Activities other than copying, distribution and modification are
  16640.      not covered by this License; they are outside its scope.  The act
  16641.      of running the Program is not restricted, and the output from the
  16642.      Program is covered only if its contents constitute a work based on
  16643.      the Program (independent of having been made by running the
  16644.      Program).  Whether that is true depends on what the Program does.
  16645.  
  16646.   1. You may copy and distribute verbatim copies of the Program's
  16647.      source code as you receive it, in any medium, provided that you
  16648.      conspicuously and appropriately publish on each copy an appropriate
  16649.      copyright notice and disclaimer of warranty; keep intact all the
  16650.      notices that refer to this License and to the absence of any
  16651.      warranty; and give any other recipients of the Program a copy of
  16652.      this License along with the Program.
  16653.  
  16654.      You may charge a fee for the physical act of transferring a copy,
  16655.      and you may at your option offer warranty protection in exchange
  16656.      for a fee.
  16657.  
  16658.   2. You may modify your copy or copies of the Program or any portion
  16659.      of it, thus forming a work based on the Program, and copy and
  16660.      distribute such modifications or work under the terms of Section 1
  16661.      above, provided that you also meet all of these conditions:
  16662.  
  16663.        a. You must cause the modified files to carry prominent notices
  16664.           stating that you changed the files and the date of any change.
  16665.  
  16666.        b. You must cause any work that you distribute or publish, that
  16667.           in whole or in part contains or is derived from the Program
  16668.           or any part thereof, to be licensed as a whole at no charge
  16669.           to all third parties under the terms of this License.
  16670.  
  16671.        c. If the modified program normally reads commands interactively
  16672.           when run, you must cause it, when started running for such
  16673.           interactive use in the most ordinary way, to print or display
  16674.           an announcement including an appropriate copyright notice and
  16675.           a notice that there is no warranty (or else, saying that you
  16676.           provide a warranty) and that users may redistribute the
  16677.           program under these conditions, and telling the user how to
  16678.           view a copy of this License.  (Exception: if the Program
  16679.           itself is interactive but does not normally print such an
  16680.           announcement, your work based on the Program is not required
  16681.           to print an announcement.)
  16682.  
  16683.      These requirements apply to the modified work as a whole.  If
  16684.      identifiable sections of that work are not derived from the
  16685.      Program, and can be reasonably considered independent and separate
  16686.      works in themselves, then this License, and its terms, do not
  16687.      apply to those sections when you distribute them as separate
  16688.      works.  But when you distribute the same sections as part of a
  16689.      whole which is a work based on the Program, the distribution of
  16690.      the whole must be on the terms of this License, whose permissions
  16691.      for other licensees extend to the entire whole, and thus to each
  16692.      and every part regardless of who wrote it.
  16693.  
  16694.      Thus, it is not the intent of this section to claim rights or
  16695.      contest your rights to work written entirely by you; rather, the
  16696.      intent is to exercise the right to control the distribution of
  16697.      derivative or collective works based on the Program.
  16698.  
  16699.      In addition, mere aggregation of another work not based on the
  16700.      Program with the Program (or with a work based on the Program) on
  16701.      a volume of a storage or distribution medium does not bring the
  16702.      other work under the scope of this License.
  16703.  
  16704.   3. You may copy and distribute the Program (or a work based on it,
  16705.      under Section 2) in object code or executable form under the terms
  16706.      of Sections 1 and 2 above provided that you also do one of the
  16707.      following:
  16708.  
  16709.        a. Accompany it with the complete corresponding machine-readable
  16710.           source code, which must be distributed under the terms of
  16711.           Sections 1 and 2 above on a medium customarily used for
  16712.           software interchange; or,
  16713.  
  16714.        b. Accompany it with a written offer, valid for at least three
  16715.           years, to give any third party, for a charge no more than your
  16716.           cost of physically performing source distribution, a complete
  16717.           machine-readable copy of the corresponding source code, to be
  16718.           distributed under the terms of Sections 1 and 2 above on a
  16719.           medium customarily used for software interchange; or,
  16720.  
  16721.        c. Accompany it with the information you received as to the offer
  16722.           to distribute corresponding source code.  (This alternative is
  16723.           allowed only for non-commercial distribution and only if you
  16724.           received the program in object code or executable form with
  16725.           such an offer, in accord with Subsection b above.)
  16726.  
  16727.      The source code for a work means the preferred form of the work for
  16728.      making modifications to it.  For an executable work, complete
  16729.      source code means all the source code for all modules it contains,
  16730.      plus any associated interface definition files, plus the scripts
  16731.      used to control compilation and installation of the executable.
  16732.      However, as a special exception, the source code distributed need
  16733.      not include anything that is normally distributed (in either
  16734.      source or binary form) with the major components (compiler,
  16735.      kernel, and so on) of the operating system on which the executable
  16736.      runs, unless that component itself accompanies the executable.
  16737.  
  16738.      If distribution of executable or object code is made by offering
  16739.      access to copy from a designated place, then offering equivalent
  16740.      access to copy the source code from the same place counts as
  16741.      distribution of the source code, even though third parties are not
  16742.      compelled to copy the source along with the object code.
  16743.  
  16744.   4. You may not copy, modify, sublicense, or distribute the Program
  16745.      except as expressly provided under this License.  Any attempt
  16746.      otherwise to copy, modify, sublicense or distribute the Program is
  16747.      void, and will automatically terminate your rights under this
  16748.      License.  However, parties who have received copies, or rights,
  16749.      from you under this License will not have their licenses
  16750.      terminated so long as such parties remain in full compliance.
  16751.  
  16752.   5. You are not required to accept this License, since you have not
  16753.      signed it.  However, nothing else grants you permission to modify
  16754.      or distribute the Program or its derivative works.  These actions
  16755.      are prohibited by law if you do not accept this License.
  16756.      Therefore, by modifying or distributing the Program (or any work
  16757.      based on the Program), you indicate your acceptance of this
  16758.      License to do so, and all its terms and conditions for copying,
  16759.      distributing or modifying the Program or works based on it.
  16760.  
  16761.   6. Each time you redistribute the Program (or any work based on the
  16762.      Program), the recipient automatically receives a license from the
  16763.      original licensor to copy, distribute or modify the Program
  16764.      subject to these terms and conditions.  You may not impose any
  16765.      further restrictions on the recipients' exercise of the rights
  16766.      granted herein.  You are not responsible for enforcing compliance
  16767.      by third parties to this License.
  16768.  
  16769.   7. If, as a consequence of a court judgment or allegation of patent
  16770.      infringement or for any other reason (not limited to patent
  16771.      issues), conditions are imposed on you (whether by court order,
  16772.      agreement or otherwise) that contradict the conditions of this
  16773.      License, they do not excuse you from the conditions of this
  16774.      License.  If you cannot distribute so as to satisfy simultaneously
  16775.      your obligations under this License and any other pertinent
  16776.      obligations, then as a consequence you may not distribute the
  16777.      Program at all.  For example, if a patent license would not permit
  16778.      royalty-free redistribution of the Program by all those who
  16779.      receive copies directly or indirectly through you, then the only
  16780.      way you could satisfy both it and this License would be to refrain
  16781.      entirely from distribution of the Program.
  16782.  
  16783.      If any portion of this section is held invalid or unenforceable
  16784.      under any particular circumstance, the balance of the section is
  16785.      intended to apply and the section as a whole is intended to apply
  16786.      in other circumstances.
  16787.  
  16788.      It is not the purpose of this section to induce you to infringe any
  16789.      patents or other property right claims or to contest validity of
  16790.      any such claims; this section has the sole purpose of protecting
  16791.      the integrity of the free software distribution system, which is
  16792.      implemented by public license practices.  Many people have made
  16793.      generous contributions to the wide range of software distributed
  16794.      through that system in reliance on consistent application of that
  16795.      system; it is up to the author/donor to decide if he or she is
  16796.      willing to distribute software through any other system and a
  16797.      licensee cannot impose that choice.
  16798.  
  16799.      This section is intended to make thoroughly clear what is believed
  16800.      to be a consequence of the rest of this License.
  16801.  
  16802.   8. If the distribution and/or use of the Program is restricted in
  16803.      certain countries either by patents or by copyrighted interfaces,
  16804.      the original copyright holder who places the Program under this
  16805.      License may add an explicit geographical distribution limitation
  16806.      excluding those countries, so that distribution is permitted only
  16807.      in or among countries not thus excluded.  In such case, this
  16808.      License incorporates the limitation as if written in the body of
  16809.      this License.
  16810.  
  16811.   9. The Free Software Foundation may publish revised and/or new
  16812.      versions of the General Public License from time to time.  Such
  16813.      new versions will be similar in spirit to the present version, but
  16814.      may differ in detail to address new problems or concerns.
  16815.  
  16816.      Each version is given a distinguishing version number.  If the
  16817.      Program specifies a version number of this License which applies
  16818.      to it and "any later version", you have the option of following
  16819.      the terms and conditions either of that version or of any later
  16820.      version published by the Free Software Foundation.  If the Program
  16821.      does not specify a version number of this License, you may choose
  16822.      any version ever published by the Free Software Foundation.
  16823.  
  16824.  10. If you wish to incorporate parts of the Program into other free
  16825.      programs whose distribution conditions are different, write to the
  16826.      author to ask for permission.  For software which is copyrighted
  16827.      by the Free Software Foundation, write to the Free Software
  16828.      Foundation; we sometimes make exceptions for this.  Our decision
  16829.      will be guided by the two goals of preserving the free status of
  16830.      all derivatives of our free software and of promoting the sharing
  16831.      and reuse of software generally.
  16832.  
  16833.                                 NO WARRANTY
  16834.  
  16835.  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO
  16836.      WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE
  16837.      LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
  16838.      HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT
  16839.      WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT
  16840.      NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  16841.      FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS TO THE
  16842.      QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
  16843.      PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY
  16844.      SERVICING, REPAIR OR CORRECTION.
  16845.  
  16846.  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
  16847.      WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY
  16848.      MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE
  16849.      LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL,
  16850.      INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR
  16851.      INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
  16852.      DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU
  16853.      OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY
  16854.      OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN
  16855.      ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
  16856.  
  16857.                       END OF TERMS AND CONDITIONS
  16858.  
  16859. How to Apply These Terms to Your New Programs
  16860. =============================================
  16861.  
  16862.    If you develop a new program, and you want it to be of the greatest
  16863. possible use to the public, the best way to achieve this is to make it
  16864. free software which everyone can redistribute and change under these
  16865. terms.
  16866.  
  16867.    To do so, attach the following notices to the program.  It is safest
  16868. to attach them to the start of each source file to most effectively
  16869. convey the exclusion of warranty; and each file should have at least
  16870. the "copyright" line and a pointer to where the full notice is found.
  16871.  
  16872.      ONE LINE TO GIVE THE PROGRAM'S NAME AND AN IDEA OF WHAT IT DOES.
  16873.      Copyright (C) 19YY  NAME OF AUTHOR
  16874.      
  16875.      This program is free software; you can redistribute it and/or
  16876.      modify it under the terms of the GNU General Public License
  16877.      as published by the Free Software Foundation; either version 2
  16878.      of the License, or (at your option) any later version.
  16879.      
  16880.      This program is distributed in the hope that it will be useful,
  16881.      but WITHOUT ANY WARRANTY; without even the implied warranty of
  16882.      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  16883.      GNU General Public License for more details.
  16884.      
  16885.      You should have received a copy of the GNU General Public License
  16886.      along with this program; if not, write to the Free Software
  16887.      Foundation, Inc., 59 Temple Place --- Suite 330, Boston, MA 02111-1307, USA.
  16888.  
  16889.    Also add information on how to contact you by electronic and paper
  16890. mail.
  16891.  
  16892.    If the program is interactive, make it output a short notice like
  16893. this when it starts in an interactive mode:
  16894.  
  16895.      Gnomovision version 69, Copyright (C) 19YY NAME OF AUTHOR
  16896.      Gnomovision comes with ABSOLUTELY NO WARRANTY; for details
  16897.      type `show w'.  This is free software, and you are welcome
  16898.      to redistribute it under certain conditions; type `show c'
  16899.      for details.
  16900.  
  16901.    The hypothetical commands `show w' and `show c' should show the
  16902. appropriate parts of the General Public License.  Of course, the
  16903. commands you use may be called something other than `show w' and `show
  16904. c'; they could even be mouse-clicks or menu items--whatever suits your
  16905. program.
  16906.  
  16907.    You should also get your employer (if you work as a programmer) or
  16908. your school, if any, to sign a "copyright disclaimer" for the program,
  16909. if necessary.  Here is a sample; alter the names:
  16910.  
  16911.      Yoyodyne, Inc., hereby disclaims all copyright
  16912.      interest in the program `Gnomovision'
  16913.      (which makes passes at compilers) written
  16914.      by James Hacker.
  16915.      
  16916.      SIGNATURE OF TY COON, 1 April 1989
  16917.      Ty Coon, President of Vice
  16918.  
  16919.    This General Public License does not permit incorporating your
  16920. program into proprietary programs.  If your program is a subroutine
  16921. library, you may consider it more useful to permit linking proprietary
  16922. applications with the library.  If this is what you want to do, use the
  16923. GNU Library General Public License instead of this License.
  16924.  
  16925. 
  16926. File: gawk.info,  Node: Index,  Prev: Copying,  Up: Top
  16927.  
  16928. Index
  16929. *****
  16930.  
  16931. * Menu:
  16932.  
  16933. * != operator:                          Typing and Comparison.
  16934. * ! operator:                           Boolean Ops.
  16935. * !~ operator <1>:                      Regexp Constants.
  16936. * !~ operator <1>:                      Computed Regexps.
  16937. * !~ operator <1>:                      Typing and Comparison.
  16938. * !~ operator <1>:                      Case-sensitivity.
  16939. * !~ operator:                          Regexp Usage.
  16940. * #! (executable scripts):              Executable Scripts.
  16941. * # (comment):                          Comments.
  16942. * $ (field operator):                   Fields.
  16943. * && operator:                          Boolean Ops.
  16944. * -assign option:                       Options.
  16945. * -compat option:                       Options.
  16946. * -copyleft option:                     Options.
  16947. * -copyright option:                    Options.
  16948. * -field-separator option:              Options.
  16949. * -file option:                         Options.
  16950. * -help option:                         Options.
  16951. * -lint-old option:                     Options.
  16952. * -lint option:                         Options.
  16953. * -posix option:                        Options.
  16954. * -source option:                       Options.
  16955. * -traditional option:                  Options.
  16956. * -usage option:                        Options.
  16957. * -version option:                      Options.
  16958. * -f option:                            Long.
  16959. * -F option <1>:                        Command Line Field Separator.
  16960. * -F option:                            Options.
  16961. * -v option:                            Options.
  16962. * -W option:                            Options.
  16963. * <= operator:                          Typing and Comparison.
  16964. * < operator:                           Typing and Comparison.
  16965. * == operator:                          Typing and Comparison.
  16966. * >= operator:                          Typing and Comparison.
  16967. * > operator:                           Typing and Comparison.
  16968. * \' regexp operator:                   GNU Regexp Operators.
  16969. * \< regexp operator:                   GNU Regexp Operators.
  16970. * \> regexp operator:                   GNU Regexp Operators.
  16971. * \` regexp operator:                   GNU Regexp Operators.
  16972. * \B regexp operator:                   GNU Regexp Operators.
  16973. * \w regexp operator:                   GNU Regexp Operators.
  16974. * \y regexp operator:                   GNU Regexp Operators.
  16975. * assert, C version:                    Assert Function.
  16976. * AWKPATH environment variable:         AWKPATH Variable.
  16977. * awksed:                               Simple Sed.
  16978. * awk language, POSIX version <1>:      Escape Sequences.
  16979. * awk language, POSIX version <1>:      Regexp Operators.
  16980. * awk language, POSIX version <1>:      Field Splitting Summary.
  16981. * awk language, POSIX version <1>:      Regexp Operators.
  16982. * awk language, POSIX version <1>:      Conversion.
  16983. * awk language, POSIX version <1>:      Precedence.
  16984. * awk language, POSIX version <1>:      Next Statement.
  16985. * awk language, POSIX version <1>:      OFMT.
  16986. * awk language, POSIX version <1>:      Continue Statement.
  16987. * awk language, POSIX version <1>:      Arithmetic Ops.
  16988. * awk language, POSIX version <1>:      Format Modifiers.
  16989. * awk language, POSIX version <1>:      Definition Syntax.
  16990. * awk language, POSIX version <1>:      String Functions.
  16991. * awk language, POSIX version <1>:      User-modified.
  16992. * awk language, POSIX version <1>:      Precedence.
  16993. * awk language, POSIX version <1>:      Assignment Ops.
  16994. * awk language, POSIX version:          Break Statement.
  16995. * awk language, V.4 version <1>:        Escape Sequences.
  16996. * awk language, V.4 version <1>:        SVR4.
  16997. * awk language, V.4 version:            Escape Sequences.
  16998. * BEGIN special pattern:                BEGIN/END.
  16999. * break statement:                      Break Statement.
  17000. * break, outside of loops:              Break Statement.
  17001. * comp.lang.awk:                        Bugs.
  17002. * continue statement:                   Continue Statement.
  17003. * continue, outside of loops:           Continue Statement.
  17004. * csh, backslash continuation <1>:      More Complex.
  17005. * csh, backslash continuation:          Statements/Lines.
  17006. * custom.h configuration file:          Configuration Philosophy.
  17007. * cut utility:                          Cut Program.
  17008. * delete statement:                     Delete.
  17009. * egrep <1>:                            Regexp Operators.
  17010. * egrep:                                One-shot.
  17011. * egrep utility:                        Egrep Program.
  17012. * END special pattern:                  BEGIN/END.
  17013. * exit statement:                       Exit Statement.
  17014. * for (x in ...):                       Scanning an Array.
  17015. * for statement:                        For Statement.
  17016. * ftp, anonymous <1>:                   Other Versions.
  17017. * ftp, anonymous:                       Getting.
  17018. * gawk coding style:                    Adding Code.
  17019. * getgrent, C version:                  Group Functions.
  17020. * getline, return values:               Getline Intro.
  17021. * getopt, C version:                    Getopt Function.
  17022. * getpwent, C version:                  Passwd Functions.
  17023. * grcat program:                        Group Functions.
  17024. * id utility:                           Id Program.
  17025. * if-else statement:                    If Statement.
  17026. * in operator:                          Typing and Comparison.
  17027. * mawk:                                 Other Versions.
  17028. * next file statement:                  Nextfile Statement.
  17029. * nextfile function:                    Nextfile Function.
  17030. * nextfile statement:                   Nextfile Statement.
  17031. * next statement:                       Next Statement.
  17032. * POSIXLY_CORRECT environment variable: Options.
  17033. * printf statement, syntax of:          Basic Printf.
  17034. * printf, format-control characters:    Control Letters.
  17035. * printf, modifiers:                    Format Modifiers.
  17036. * print statement:                      Print.
  17037. * pwcat program:                        Passwd Functions.
  17038. * return statement:                     Return Statement.
  17039. * sed utility <1>:                      Simple Sed.
  17040. * sed utility <1>:                      Igawk Program.
  17041. * sed utility:                          Field Splitting Summary.
  17042. * split utility:                        Split Program.
  17043. * tee utility:                          Tee Program.
  17044. * uniq utility:                         Uniq Program.
  17045. * wc utility:                           Wc Program.
  17046. * while statement:                      While Statement.
  17047. * || operator:                          Boolean Ops.
  17048. * ~ operator <1>:                       Typing and Comparison.
  17049. * ~ operator <1>:                       Regexp Constants.
  17050. * ~ operator <1>:                       Computed Regexps.
  17051. * ~ operator <1>:                       Regexp Usage.
  17052. * ~ operator:                           Case-sensitivity.
  17053. * /dev/fd:                              Special Files.
  17054. * /dev/pgrpid:                          Special Files.
  17055. * /dev/pid:                             Special Files.
  17056. * /dev/ppid:                            Special Files.
  17057. * /dev/stderr:                          Special Files.
  17058. * /dev/stdin:                           Special Files.
  17059. * /dev/stdout:                          Special Files.
  17060. * /dev/user <1>:                        Passwd Functions.
  17061. * /dev/user:                            Special Files.
  17062. * BBS-list file:                        Sample Data Files.
  17063. * inventory-shipped file:               Sample Data Files.
  17064. * _gr_init:                             Group Functions.
  17065. * _pw_init:                             Passwd Functions.
  17066. * _tm_addup:                            Mktime Function.
  17067. * _tm_isleap:                           Mktime Function.
  17068. * accessing fields:                     Fields.
  17069. * account information <1>:              Group Functions.
  17070. * account information:                  Passwd Functions.
  17071. * acronym:                              History.
  17072. * action, curly braces:                 Action Overview.
  17073. * action, default:                      Very Simple.
  17074. * action, definition of:                Action Overview.
  17075. * action, empty:                        Very Simple.
  17076. * action, separating statements:        Action Overview.
  17077. * adding new features:                  Adding Code.
  17078. * addition:                             Arithmetic Ops.
  17079. * Aho, Alfred:                          History.
  17080. * alarm.awk:                            Alarm Program.
  17081. * amiga:                                Amiga Installation.
  17082. * anchors in regexps:                   Regexp Operators.
  17083. * and operator:                         Boolean Ops.
  17084. * anonymous ftp <1>:                    Getting.
  17085. * anonymous ftp:                        Other Versions.
  17086. * applications of awk:                  When.
  17087. * ARGC:                                 Auto-set.
  17088. * ARGIND <1>:                           Auto-set.
  17089. * ARGIND:                               Other Arguments.
  17090. * argument processing:                  Getopt Function.
  17091. * arguments in function call:           Function Calls.
  17092. * arguments, command line:              Invoking Gawk.
  17093. * ARGV <1>:                             Other Arguments.
  17094. * ARGV:                                 Auto-set.
  17095. * arithmetic operators:                 Arithmetic Ops.
  17096. * array assignment:                     Assigning Elements.
  17097. * array reference:                      Reference to Elements.
  17098. * array subscripts, uninitialized variables: Uninitialized Subscripts.
  17099. * arrays:                               Array Intro.
  17100. * arrays, associative:                  Array Intro.
  17101. * arrays, definition of:                Array Intro.
  17102. * arrays, deleting an element:          Delete.
  17103. * arrays, deleting entire contents:     Delete.
  17104. * arrays, multi-dimensional subscripts: Multi-dimensional.
  17105. * arrays, presence of elements:         Reference to Elements.
  17106. * arrays, sparse:                       Array Intro.
  17107. * arrays, special for statement:        Scanning an Array.
  17108. * arrays, the in operator:              Reference to Elements.
  17109. * ASCII:                                Ordinal Functions.
  17110. * assert:                               Assert Function.
  17111. * assertions:                           Assert Function.
  17112. * assignment operators:                 Assignment Ops.
  17113. * assignment to fields:                 Changing Fields.
  17114. * associative arrays:                   Array Intro.
  17115. * atan2:                                Numeric Functions.
  17116. * atari:                                Atari Installation.
  17117. * automatic initialization:             More Complex.
  17118. * backslash continuation <1>:           Statements/Lines.
  17119. * backslash continuation:               Assert Function.
  17120. * backslash continuation in csh <1>:    Statements/Lines.
  17121. * backslash continuation in csh:        More Complex.
  17122. * basic function of awk:                Getting Started.
  17123. * beginfile:                            Filetrans Function.
  17124. * body of a loop:                       While Statement.
  17125. * book, using this:                     This Manual.
  17126. * boolean expressions:                  Boolean Ops.
  17127. * boolean operators:                    Boolean Ops.
  17128. * Brennan, Michael <1>:                 Other Versions.
  17129. * Brennan, Michael <1>:                 Delete.
  17130. * Brennan, Michael:                     Simple Sed.
  17131. * buffer matching operators:            GNU Regexp Operators.
  17132. * buffering output:                     I/O Functions.
  17133. * buffers, flushing:                    I/O Functions.
  17134. * bugs, known in gawk:                  Known Bugs.
  17135. * built-in functions:                   Built-in.
  17136. * built-in variables:                   Built-in Variables.
  17137. * built-in variables, convey information: Auto-set.
  17138. * built-in variables, user modifiable:  User-modified.
  17139. * call by reference:                    Function Caveats.
  17140. * call by value:                        Function Caveats.
  17141. * calling a function <1>:               Function Caveats.
  17142. * calling a function:                   Function Calls.
  17143. * case conversion:                      String Functions.
  17144. * case sensitivity:                     Case-sensitivity.
  17145. * changing contents of a field:         Changing Fields.
  17146. * changing the record separator:        Records.
  17147. * character classes:                    Regexp Operators.
  17148. * character encodings:                  Ordinal Functions.
  17149. * character list:                       Regexp Operators.
  17150. * character list, complemented:         Regexp Operators.
  17151. * character sets:                       Ordinal Functions.
  17152. * chr:                                  Ordinal Functions.
  17153. * close <1>:                            Close Files And Pipes.
  17154. * close:                                I/O Functions.
  17155. * closing input files and pipes:        Close Files And Pipes.
  17156. * closing output files and pipes:       Close Files And Pipes.
  17157. * coding style used in gawk:            Adding Code.
  17158. * collating elements:                   Regexp Operators.
  17159. * collating symbols:                    Regexp Operators.
  17160. * command line:                         Invoking Gawk.
  17161. * command line formats:                 Running gawk.
  17162. * command line, setting FS on:          Command Line Field Separator.
  17163. * comments:                             Comments.
  17164. * common mistakes <1>:                  Typing and Comparison.
  17165. * common mistakes <1>:                  Computed Regexps.
  17166. * common mistakes <1>:                  Print Examples.
  17167. * common mistakes:                      Basic Field Splitting.
  17168. * comparison expressions:               Typing and Comparison.
  17169. * comparisons, string vs. regexp:       Typing and Comparison.
  17170. * compatibility mode <1>:               Options.
  17171. * compatibility mode:                   POSIX/GNU.
  17172. * complemented character list:          Regexp Operators.
  17173. * compound statement:                   Statements.
  17174. * computed regular expressions:         Computed Regexps.
  17175. * concatenation:                        Concatenation.
  17176. * conditional expression:               Conditional Exp.
  17177. * configuring gawk:                     Configuration Philosophy.
  17178. * constants, types of:                  Constants.
  17179. * continuation of lines:                Statements/Lines.
  17180. * control statement:                    Statements.
  17181. * conversion of case:                   String Functions.
  17182. * conversion of strings and numbers:    Conversion.
  17183. * conversions, during subscripting:     Numeric Array Subscripts.
  17184. * converting dates to timestamps:       Mktime Function.
  17185. * CONVFMT <1>:                          User-modified.
  17186. * CONVFMT <1>:                          Conversion.
  17187. * CONVFMT:                              Numeric Array Subscripts.
  17188. * cos:                                  Numeric Functions.
  17189. * curly braces:                         Action Overview.
  17190. * cut.awk:                              Cut Program.
  17191. * d.c., see "dark corner":              This Manual.
  17192. * dark corner <1>:                      Invoking Gawk.
  17193. * dark corner <1>:                      Uninitialized Subscripts.
  17194. * dark corner <1>:                      This Manual.
  17195. * dark corner <1>:                      Other Arguments.
  17196. * dark corner <1>:                      Control Letters.
  17197. * dark corner <1>:                      OFMT.
  17198. * dark corner <1>:                      Plain Getline.
  17199. * dark corner <1>:                      String Functions.
  17200. * dark corner <1>:                      Format Modifiers.
  17201. * dark corner <1>:                      Conversion.
  17202. * dark corner <1>:                      Multiple Line.
  17203. * dark corner <1>:                      Continue Statement.
  17204. * dark corner <1>:                      Exit Statement.
  17205. * dark corner <1>:                      Break Statement.
  17206. * dark corner <1>:                      Assignment Options.
  17207. * dark corner <1>:                      Truth Values.
  17208. * dark corner <1>:                      Single Character Fields.
  17209. * dark corner <1>:                      Auto-set.
  17210. * dark corner <1>:                      Using Constant Regexps.
  17211. * dark corner <1>:                      Auto-set.
  17212. * dark corner <1>:                      Records.
  17213. * dark corner <1>:                      Field Splitting Summary.
  17214. * dark corner <1>:                      Escape Sequences.
  17215. * dark corner:                          Using BEGIN/END.
  17216. * data-driven languages:                Getting Started.
  17217. * dates, converting to timestamps:      Mktime Function.
  17218. * decrement operators:                  Increment Ops.
  17219. * default action:                       Very Simple.
  17220. * default pattern:                      Very Simple.
  17221. * defining functions:                   Definition Syntax.
  17222. * Deifik, Scott <1>:                    Acknowledgements.
  17223. * Deifik, Scott:                        Bugs.
  17224. * deleting elements of arrays:          Delete.
  17225. * deleting entire arrays:               Delete.
  17226. * deprecated features:                  Obsolete.
  17227. * deprecated options:                   Obsolete.
  17228. * differences between gawk and awk <1>: Using Constant Regexps.
  17229. * differences between gawk and awk <1>: Scalar Constants.
  17230. * differences between gawk and awk <1>: Redirection.
  17231. * differences between gawk and awk <1>: I/O And BEGIN/END.
  17232. * differences between gawk and awk <1>: Records.
  17233. * differences between gawk and awk <1>: Conditional Exp.
  17234. * differences between gawk and awk <1>: Case-sensitivity.
  17235. * differences between gawk and awk <1>: Getline Summary.
  17236. * differences between gawk and awk <1>: Close Files And Pipes.
  17237. * differences between gawk and awk <1>: Records.
  17238. * differences between gawk and awk <1>: Close Files And Pipes.
  17239. * differences between gawk and awk <1>: Getline Intro.
  17240. * differences between gawk and awk <1>: Nextfile Statement.
  17241. * differences between gawk and awk <1>: Calling Built-in.
  17242. * differences between gawk and awk <1>: AWKPATH Variable.
  17243. * differences between gawk and awk <1>: String Functions.
  17244. * differences between gawk and awk <1>: Special Files.
  17245. * differences between gawk and awk <1>: Arithmetic Ops.
  17246. * differences between gawk and awk <1>: String Functions.
  17247. * differences between gawk and awk <1>: Delete.
  17248. * differences between gawk and awk:     Single Character Fields.
  17249. * directory search:                     AWKPATH Variable.
  17250. * division:                             Arithmetic Ops.
  17251. * documenting awk programs <1>:         Comments.
  17252. * documenting awk programs:             Library Names.
  17253. * dupword.awk:                          Dupword Program.
  17254. * dynamic regular expressions:          Computed Regexps.
  17255. * EBCDIC:                               Ordinal Functions.
  17256. * egrep.awk:                            Egrep Program.
  17257. * element assignment:                   Assigning Elements.
  17258. * element of array:                     Reference to Elements.
  17259. * empty action:                         Very Simple.
  17260. * empty pattern:                        Empty.
  17261. * empty program:                        Invoking Gawk.
  17262. * empty string <1>:                     Records.
  17263. * empty string <1>:                     Conversion.
  17264. * empty string <1>:                     Truth Values.
  17265. * empty string:                         Regexp Field Splitting.
  17266. * endfile:                              Filetrans Function.
  17267. * endgrent:                             Group Functions.
  17268. * endpwent:                             Passwd Functions.
  17269. * ENVIRON:                              Auto-set.
  17270. * environment variable, AWKPATH:        AWKPATH Variable.
  17271. * environment variable, POSIXLY_CORRECT: Options.
  17272. * equivalence classes:                  Regexp Operators.
  17273. * ERRNO <1>:                            Close Files And Pipes.
  17274. * ERRNO <1>:                            Auto-set.
  17275. * ERRNO:                                Getline Intro.
  17276. * errors, common <1>:                   Computed Regexps.
  17277. * errors, common <1>:                   Basic Field Splitting.
  17278. * errors, common <1>:                   Print Examples.
  17279. * errors, common:                       Typing and Comparison.
  17280. * escape processing, sub et. al.:       String Functions.
  17281. * escape sequence notation:             Escape Sequences.
  17282. * evaluation, order of:                 Calling Built-in.
  17283. * examining fields:                     Fields.
  17284. * executable scripts:                   Executable Scripts.
  17285. * exp:                                  Numeric Functions.
  17286. * explicit input:                       Getline.
  17287. * exponentiation:                       Arithmetic Ops.
  17288. * expression:                           Expressions.
  17289. * expression, assignment:               Assignment Ops.
  17290. * expression, boolean:                  Boolean Ops.
  17291. * expression, comparison:               Typing and Comparison.
  17292. * expression, conditional:              Conditional Exp.
  17293. * expression, matching:                 Typing and Comparison.
  17294. * extract.awk:                          Extract Program.
  17295. * features, adding:                     Adding Code.
  17296. * fflush:                               I/O Functions.
  17297. * field operator $:                     Fields.
  17298. * field separator, FS:                  Basic Field Splitting.
  17299. * field separator, choice of:           Basic Field Splitting.
  17300. * field separator, on command line:     Command Line Field Separator.
  17301. * field, changing contents of:          Changing Fields.
  17302. * fields:                               Fields.
  17303. * fields, separating:                   Basic Field Splitting.
  17304. * FIELDWIDTHS:                          User-modified.
  17305. * file descriptors:                     Special Files.
  17306. * file, awk program:                    Long.
  17307. * FILENAME <1>:                         Auto-set.
  17308. * FILENAME:                             Reading Files.
  17309. * Fish, Fred:                           Bugs.
  17310. * flushing buffers:                     I/O Functions.
  17311. * FNR <1>:                              Auto-set.
  17312. * FNR:                                  Records.
  17313. * format specifier:                     Control Letters.
  17314. * format string:                        Basic Printf.
  17315. * format, numeric output:               OFMT.
  17316. * formatted output:                     Printf.
  17317. * formatted timestamps:                 Gettimeofday Function.
  17318. * Free Software Foundation <1>:         Manual History.
  17319. * Free Software Foundation:             Getting.
  17320. * FreeBSD:                              Manual History.
  17321. * Friedl, Jeffrey:                      Acknowledgements.
  17322. * FS <1>:                               Basic Field Splitting.
  17323. * FS:                                   User-modified.
  17324. * function call <1>:                    Function Calls.
  17325. * function call:                        Function Caveats.
  17326. * function definition:                  Definition Syntax.
  17327. * function, recursive:                  Definition Syntax.
  17328. * functions, undefined:                 Function Caveats.
  17329. * functions, user-defined:              User-defined.
  17330. * gensub:                               String Functions.
  17331. * getgrent:                             Group Functions.
  17332. * getgrgid:                             Group Functions.
  17333. * getgrnam:                             Group Functions.
  17334. * getgruser:                            Group Functions.
  17335. * getline:                              Getline.
  17336. * getopt:                               Getopt Function.
  17337. * getpwent:                             Passwd Functions.
  17338. * getpwnam:                             Passwd Functions.
  17339. * getpwuid:                             Passwd Functions.
  17340. * gettimeofday:                         Gettimeofday Function.
  17341. * getting gawk:                         Getting.
  17342. * GNU Project:                          Manual History.
  17343. * grcat.c:                              Group Functions.
  17344. * group file:                           Group Functions.
  17345. * group information:                    Group Functions.
  17346. * gsub:                                 String Functions.
  17347. * Hankerson, Darrel <1>:                Acknowledgements.
  17348. * Hankerson, Darrel:                    Bugs.
  17349. * historical features <1>:              String Functions.
  17350. * historical features <1>:              Break Statement.
  17351. * historical features <1>:              Command Line Field Separator.
  17352. * historical features <1>:              Historical Features.
  17353. * historical features:                  Continue Statement.
  17354. * history of awk:                       History.
  17355. * histsort.awk:                         History Sorting.
  17356. * how awk works:                        Two Rules.
  17357. * Hughes, Phil:                         Acknowledgements.
  17358. * I/O from BEGIN and END:               I/O And BEGIN/END.
  17359. * id.awk:                               Id Program.
  17360. * igawk.sh:                             Igawk Program.
  17361. * IGNORECASE <1>:                       User-modified.
  17362. * IGNORECASE:                           Case-sensitivity.
  17363. * ignoring case:                        Case-sensitivity.
  17364. * implementation limits <1>:            Redirection.
  17365. * implementation limits:                Getline Summary.
  17366. * increment operators:                  Increment Ops.
  17367. * index:                                String Functions.
  17368. * initialization, automatic:            More Complex.
  17369. * input:                                Reading Files.
  17370. * input file, sample:                   Sample Data Files.
  17371. * input files, skipping:                Nextfile Function.
  17372. * input pipeline:                       Getline/Pipe.
  17373. * input redirection:                    Getline/File.
  17374. * input, getline command:               Getline.
  17375. * input, explicit:                      Getline.
  17376. * input, multiple line records:         Multiple Line.
  17377. * input, standard:                      Read Terminal.
  17378. * installation, amiga:                  Amiga Installation.
  17379. * installation, atari:                  Atari Installation.
  17380. * installation, MS-DOS and OS/2:        PC Installation.
  17381. * installation, unix:                   Quick Installation.
  17382. * installation, vms:                    VMS Installation.
  17383. * int:                                  Numeric Functions.
  17384. * interaction, awk and other programs:  I/O Functions.
  17385. * interval expressions:                 Regexp Operators.
  17386. * invocation of gawk:                   Invoking Gawk.
  17387. * ISO 8601:                             Time Functions.
  17388. * ISO 8859-1 <1>:                       Glossary.
  17389. * ISO 8859-1:                           Case-sensitivity.
  17390. * ISO Latin-1 <1>:                      Case-sensitivity.
  17391. * ISO Latin-1:                          Glossary.
  17392. * Jaegermann, Michal <1>:               Bugs.
  17393. * Jaegermann, Michal:                   Acknowledgements.
  17394. * join:                                 Join Function.
  17395. * Kernighan, Brian <1>:                 History.
  17396. * Kernighan, Brian <1>:                 BTL.
  17397. * Kernighan, Brian <1>:                 Acknowledgements.
  17398. * Kernighan, Brian:                     Other Versions.
  17399. * known bugs:                           Known Bugs.
  17400. * labels.awk:                           Labels Program.
  17401. * language, awk:                        This Manual.
  17402. * language, data-driven:                Getting Started.
  17403. * language, procedural:                 Getting Started.
  17404. * leftmost longest match <1>:           Multiple Line.
  17405. * leftmost longest match:               Leftmost Longest.
  17406. * length:                               String Functions.
  17407. * limitations <1>:                      Redirection.
  17408. * limitations:                          Getline Summary.
  17409. * line break:                           Statements/Lines.
  17410. * line continuation <1>:                Boolean Ops.
  17411. * line continuation <1>:                Statements/Lines.
  17412. * line continuation <1>:                Conditional Exp.
  17413. * line continuation:                    Print Examples.
  17414. * Linux <1>:                            Manual History.
  17415. * Linux:                                Atari Compiling.
  17416. * locale, definition of:                Time Functions.
  17417. * log:                                  Numeric Functions.
  17418. * logical false:                        Truth Values.
  17419. * logical operations:                   Boolean Ops.
  17420. * logical true:                         Truth Values.
  17421. * login information:                    Passwd Functions.
  17422. * long options:                         Invoking Gawk.
  17423. * loop:                                 While Statement.
  17424. * loops, exiting:                       Break Statement.
  17425. * lvalue:                               Assignment Ops.
  17426. * mark parity:                          Ordinal Functions.
  17427. * match:                                String Functions.
  17428. * matching ranges of lines:             Ranges.
  17429. * matching, leftmost longest <1>:       Leftmost Longest.
  17430. * matching, leftmost longest:           Multiple Line.
  17431. * merging strings:                      Join Function.
  17432. * metacharacters:                       Regexp Operators.
  17433. * mistakes, common <1>:                 Computed Regexps.
  17434. * mistakes, common <1>:                 Print Examples.
  17435. * mistakes, common <1>:                 Typing and Comparison.
  17436. * mistakes, common:                     Basic Field Splitting.
  17437. * mktime:                               Mktime Function.
  17438. * modifiers (in format specifiers):     Format Modifiers.
  17439. * multi-dimensional subscripts:         Multi-dimensional.
  17440. * multiple line records:                Multiple Line.
  17441. * multiple passes over data:            Other Arguments.
  17442. * multiple statements on one line:      Statements/Lines.
  17443. * multiplication:                       Arithmetic Ops.
  17444. * names, use of:                        Definition Syntax.
  17445. * namespace issues in awk:              Library Names.
  17446. * namespaces:                           Definition Syntax.
  17447. * NetBSD:                               Manual History.
  17448. * new awk:                              History.
  17449. * new awk vs. old awk:                  Names.
  17450. * newline:                              Statements/Lines.
  17451. * NF <1>:                               Auto-set.
  17452. * NF:                                   Fields.
  17453. * not operator:                         Boolean Ops.
  17454. * NR <1>:                               Records.
  17455. * NR:                                   Auto-set.
  17456. * null string <1>:                      Truth Values.
  17457. * null string <1>:                      Conversion.
  17458. * null string:                          Regexp Field Splitting.
  17459. * null string, as array subscript:      Uninitialized Subscripts.
  17460. * number of fields, NF:                 Fields.
  17461. * number of records, NR, FNR:           Records.
  17462. * numbers, used as subscripts:          Numeric Array Subscripts.
  17463. * numeric character values:             Ordinal Functions.
  17464. * numeric constant:                     Scalar Constants.
  17465. * numeric output format:                OFMT.
  17466. * numeric string:                       Typing and Comparison.
  17467. * numeric value:                        Scalar Constants.
  17468. * obsolete features:                    Obsolete.
  17469. * obsolete options:                     Obsolete.
  17470. * OFMT <1>:                             User-modified.
  17471. * OFMT <1>:                             OFMT.
  17472. * OFMT:                                 Conversion.
  17473. * OFS <1>:                              Output Separators.
  17474. * OFS:                                  User-modified.
  17475. * old awk:                              History.
  17476. * old awk vs. new awk:                  Names.
  17477. * one-liners:                           One-liners.
  17478. * operations, logical:                  Boolean Ops.
  17479. * operator precedence:                  Precedence.
  17480. * operators, arithmetic:                Arithmetic Ops.
  17481. * operators, assignment:                Assignment Ops.
  17482. * operators, boolean:                   Boolean Ops.
  17483. * operators, decrement:                 Increment Ops.
  17484. * operators, increment:                 Increment Ops.
  17485. * operators, regexp matching:           Regexp Usage.
  17486. * operators, relational:                Typing and Comparison.
  17487. * operators, short-circuit:             Boolean Ops.
  17488. * operators, string:                    Concatenation.
  17489. * operators, string-matching:           Regexp Usage.
  17490. * options, command line:                Invoking Gawk.
  17491. * options, long:                        Invoking Gawk.
  17492. * or operator:                          Boolean Ops.
  17493. * ord:                                  Ordinal Functions.
  17494. * order of evaluation:                  Calling Built-in.
  17495. * ORS <1>:                              User-modified.
  17496. * ORS:                                  Output Separators.
  17497. * output:                               Printing.
  17498. * output field separator, OFS:          Output Separators.
  17499. * output format specifier, OFMT:        OFMT.
  17500. * output record separator, ORS:         Output Separators.
  17501. * output redirection:                   Redirection.
  17502. * output, buffering:                    I/O Functions.
  17503. * output, formatted:                    Printf.
  17504. * output, piping:                       Redirection.
  17505. * passes, multiple:                     Other Arguments.
  17506. * password file:                        Passwd Functions.
  17507. * path, search:                         AWKPATH Variable.
  17508. * pattern, BEGIN:                       BEGIN/END.
  17509. * pattern, END:                         BEGIN/END.
  17510. * pattern, default:                     Very Simple.
  17511. * pattern, definition of:               Patterns and Actions.
  17512. * pattern, empty:                       Empty.
  17513. * pattern, range:                       Ranges.
  17514. * pattern, regular expressions:         Regexp.
  17515. * patterns, types of:                   Kinds of Patterns.
  17516. * per file initialization and clean-up: Filetrans Function.
  17517. * PERL:                                 Future Extensions.
  17518. * pipeline, input:                      Getline/Pipe.
  17519. * pipes for output:                     Redirection.
  17520. * portability issues <1>:               Delete.
  17521. * portability issues <1>:               Portability Notes.
  17522. * portability issues <1>:               Close Files And Pipes.
  17523. * portability issues <1>:               Statements/Lines.
  17524. * portability issues <1>:               I/O Functions.
  17525. * portability issues <1>:               String Functions.
  17526. * portability issues <1>:               Definition Syntax.
  17527. * portability issues:                   Escape Sequences.
  17528. * porting gawk:                         New Ports.
  17529. * POSIX awk <1>:                        Continue Statement.
  17530. * POSIX awk <1>:                        Next Statement.
  17531. * POSIX awk <1>:                        Break Statement.
  17532. * POSIX awk <1>:                        Regexp Operators.
  17533. * POSIX awk <1>:                        User-modified.
  17534. * POSIX awk <1>:                        Arithmetic Ops.
  17535. * POSIX awk <1>:                        Assignment Ops.
  17536. * POSIX awk <1>:                        Definition Syntax.
  17537. * POSIX awk <1>:                        String Functions.
  17538. * POSIX awk <1>:                        Precedence.
  17539. * POSIX awk <1>:                        String Functions.
  17540. * POSIX awk <1>:                        Conversion.
  17541. * POSIX awk <1>:                        Escape Sequences.
  17542. * POSIX awk <1>:                        OFMT.
  17543. * POSIX awk <1>:                        Field Splitting Summary.
  17544. * POSIX awk <1>:                        Format Modifiers.
  17545. * POSIX awk:                            Regexp Operators.
  17546. * POSIX mode:                           Options.
  17547. * precedence:                           Precedence.
  17548. * precedence, regexp operators:         Regexp Operators.
  17549. * printing:                             Printing.
  17550. * procedural languages:                 Getting Started.
  17551. * process information:                  Special Files.
  17552. * processing arguments:                 Getopt Function.
  17553. * program file:                         Long.
  17554. * program, awk:                         This Manual.
  17555. * program, definition of:               Getting Started.
  17556. * program, self contained:              Executable Scripts.
  17557. * programs, documenting <1>:            Comments.
  17558. * programs, documenting:                Library Names.
  17559. * pwcat.c:                              Passwd Functions.
  17560. * quotient:                             Arithmetic Ops.
  17561. * quoting, shell <1>:                   Read Terminal.
  17562. * quoting, shell:                       Long.
  17563. * Rakitzis, Byron:                      History Sorting.
  17564. * rand:                                 Numeric Functions.
  17565. * random numbers, seed of:              Numeric Functions.
  17566. * range pattern:                        Ranges.
  17567. * Rankin, Pat <1>:                      Assignment Ops.
  17568. * Rankin, Pat <1>:                      Acknowledgements.
  17569. * Rankin, Pat:                          Bugs.
  17570. * reading files:                        Reading Files.
  17571. * reading files, getline command:       Getline.
  17572. * reading files, multiple line records: Multiple Line.
  17573. * record separator, RS:                 Records.
  17574. * record terminator, RT:                Records.
  17575. * record, definition of:                Records.
  17576. * records, multiple line:               Multiple Line.
  17577. * recursive function:                   Definition Syntax.
  17578. * redirection of input:                 Getline/File.
  17579. * redirection of output:                Redirection.
  17580. * reference to array:                   Reference to Elements.
  17581. * regexp:                               Regexp.
  17582. * regexp as expression:                 Typing and Comparison.
  17583. * regexp comparison vs. string comparison: Typing and Comparison.
  17584. * regexp constant:                      Regexp Usage.
  17585. * regexp constants, difference between slashes and quotes: Computed Regexps.
  17586. * regexp match/non-match operators <1>: Regexp Usage.
  17587. * regexp match/non-match operators:     Typing and Comparison.
  17588. * regexp matching operators:            Regexp Usage.
  17589. * regexp operators:                     Regexp Operators.
  17590. * regexp operators, GNU specific:       GNU Regexp Operators.
  17591. * regexp operators, precedence of:      Regexp Operators.
  17592. * regexp, anchors:                      Regexp Operators.
  17593. * regexp, dynamic:                      Computed Regexps.
  17594. * regexp, effect of command line options: GNU Regexp Operators.
  17595. * regular expression:                   Regexp.
  17596. * regular expression metacharacters:    Regexp Operators.
  17597. * regular expressions as field separators: Basic Field Splitting.
  17598. * regular expressions as patterns:      Regexp.
  17599. * regular expressions as record separators: Records.
  17600. * regular expressions, computed:        Computed Regexps.
  17601. * relational operators:                 Typing and Comparison.
  17602. * remainder:                            Arithmetic Ops.
  17603. * removing elements of arrays:          Delete.
  17604. * RFC-1036:                             Time Functions.
  17605. * RFC-822:                              Time Functions.
  17606. * RLENGTH <1>:                          Auto-set.
  17607. * RLENGTH:                              String Functions.
  17608. * Robbins, Miriam:                      Acknowledgements.
  17609. * Rommel, Kai Uwe <1>:                  Bugs.
  17610. * Rommel, Kai Uwe:                      Acknowledgements.
  17611. * RS <1>:                               User-modified.
  17612. * RS:                                   Records.
  17613. * RSTART <1>:                           String Functions.
  17614. * RSTART:                               Auto-set.
  17615. * RT <1>:                               Auto-set.
  17616. * RT <1>:                               Multiple Line.
  17617. * RT:                                   Records.
  17618. * rule, definition of:                  Getting Started.
  17619. * running awk programs:                 Running gawk.
  17620. * running long programs:                Long.
  17621. * rvalue:                               Assignment Ops.
  17622. * sample input file:                    Sample Data Files.
  17623. * scanning an array:                    Scanning an Array.
  17624. * script, definition of:                Getting Started.
  17625. * scripts, executable:                  Executable Scripts.
  17626. * scripts, shell:                       Executable Scripts.
  17627. * search path:                          AWKPATH Variable.
  17628. * search path, for source files:        AWKPATH Variable.
  17629. * seed for random numbers:              Numeric Functions.
  17630. * self contained programs:              Executable Scripts.
  17631. * shell quoting <1>:                    Read Terminal.
  17632. * shell quoting:                        Long.
  17633. * shell scripts:                        Executable Scripts.
  17634. * short-circuit operators:              Boolean Ops.
  17635. * side effect:                          Assignment Ops.
  17636. * simple stream editor:                 Simple Sed.
  17637. * sin:                                  Numeric Functions.
  17638. * single character fields:              Single Character Fields.
  17639. * single quotes, why needed:            One-shot.
  17640. * skipping input files:                 Nextfile Function.
  17641. * skipping lines between markers:       Ranges.
  17642. * sparse arrays:                        Array Intro.
  17643. * split:                                String Functions.
  17644. * split.awk:                            Split Program.
  17645. * sprintf:                              String Functions.
  17646. * sqrt:                                 Numeric Functions.
  17647. * srand:                                Numeric Functions.
  17648. * standard error output:                Special Files.
  17649. * standard input <1>:                   Special Files.
  17650. * standard input <1>:                   Read Terminal.
  17651. * standard input:                       Reading Files.
  17652. * standard output:                      Special Files.
  17653. * statement, compound:                  Statements.
  17654. * stream editor:                        Field Splitting Summary.
  17655. * stream editor, simple:                Simple Sed.
  17656. * strftime:                             Time Functions.
  17657. * string comparison vs. regexp comparison: Typing and Comparison.
  17658. * string constants:                     Constants.
  17659. * string operators:                     Concatenation.
  17660. * string-matching operators:            Regexp Usage.
  17661. * sub:                                  String Functions.
  17662. * subscripts in arrays:                 Multi-dimensional.
  17663. * SUBSEP <1>:                           Multi-dimensional.
  17664. * SUBSEP:                               User-modified.
  17665. * substr:                               String Functions.
  17666. * subtraction:                          Arithmetic Ops.
  17667. * system:                               I/O Functions.
  17668. * systime:                              Time Functions.
  17669. * Tcl:                                  Library Names.
  17670. * tee.awk:                              Tee Program.
  17671. * terminator, record:                   Records.
  17672. * time of day:                          Time Functions.
  17673. * timestamps:                           Time Functions.
  17674. * timestamps, converting from dates:    Mktime Function.
  17675. * timestamps, formatted:                Gettimeofday Function.
  17676. * tolower:                              String Functions.
  17677. * toupper:                              String Functions.
  17678. * translate.awk:                        Translate Program.
  17679. * Trueman, David:                       Acknowledgements.
  17680. * truth values:                         Truth Values.
  17681. * type conversion:                      Conversion.
  17682. * types of variables <1>:               Assignment Ops.
  17683. * types of variables:                   Typing and Comparison.
  17684. * undefined functions:                  Function Caveats.
  17685. * undocumented features:                Undocumented.
  17686. * uninitialized variables, as array subscripts: Uninitialized Subscripts.
  17687. * uniq.awk:                             Uniq Program.
  17688. * use of comments:                      Comments.
  17689. * user information:                     Passwd Functions.
  17690. * user-defined functions:               User-defined.
  17691. * user-defined variables:               Using Variables.
  17692. * uses of awk:                          What Is Awk.
  17693. * using this book:                      This Manual.
  17694. * values of characters as numbers:      Ordinal Functions.
  17695. * variable shadowing:                   Definition Syntax.
  17696. * variable typing:                      Typing and Comparison.
  17697. * variables, user-defined:              Using Variables.
  17698. * Wall, Larry:                          Future Extensions.
  17699. * wc.awk:                               Wc Program.
  17700. * Weinberger, Peter:                    History.
  17701. * when to use awk:                      When.
  17702. * word boundaries, matching:            GNU Regexp Operators.
  17703. * word, regexp definition of:           GNU Regexp Operators.
  17704. * wordfreq.sh:                          Word Sorting.
  17705.  
  17706.  
  17707. 
  17708. Tag Table:
  17709. Node: Top1054
  17710. Node: Preface20361
  17711. Node: History21710
  17712. Node: Manual History23068
  17713. Node: Acknowledgements26658
  17714. Node: What Is Awk30283
  17715. Node: This Manual31937
  17716. Node: Conventions34579
  17717. Node: Sample Data Files35871
  17718. Node: Getting Started38954
  17719. Node: Names41262
  17720. Node: Running gawk42832
  17721. Node: One-shot43993
  17722. Node: Read Terminal45380
  17723. Node: Long46994
  17724. Node: Executable Scripts48387
  17725. Node: Comments50643
  17726. Node: Very Simple51803
  17727. Node: Two Rules53850
  17728. Node: More Complex56029
  17729. Node: Statements/Lines59145
  17730. Node: Other Features62766
  17731. Node: When63492
  17732. Node: One-liners65427
  17733. Node: Regexp68307
  17734. Node: Regexp Usage69633
  17735. Node: Escape Sequences71783
  17736. Node: Regexp Operators77235
  17737. Node: GNU Regexp Operators88184
  17738. Node: Case-sensitivity91888
  17739. Node: Leftmost Longest95004
  17740. Node: Computed Regexps96539
  17741. Node: Reading Files99196
  17742. Node: Records100964
  17743. Node: Fields107459
  17744. Node: Non-Constant Fields110405
  17745. Node: Changing Fields112692
  17746. Node: Field Separators116812
  17747. Node: Basic Field Splitting117514
  17748. Node: Regexp Field Splitting120734
  17749. Node: Single Character Fields123263
  17750. Node: Command Line Field Separator124340
  17751. Node: Field Splitting Summary127581
  17752. Node: Constant Size129600
  17753. Node: Multiple Line133637
  17754. Node: Getline139044
  17755. Node: Getline Intro140130
  17756. Node: Plain Getline141093
  17757. Node: Getline/Variable143357
  17758. Node: Getline/File144499
  17759. Node: Getline/Variable/File145450
  17760. Node: Getline/Pipe147061
  17761. Node: Getline/Variable/Pipe148788
  17762. Node: Getline Summary149531
  17763. Node: Printing150605
  17764. Node: Print151673
  17765. Node: Print Examples153773
  17766. Node: Output Separators156383
  17767. Node: OFMT158281
  17768. Node: Printf159683
  17769. Node: Basic Printf160587
  17770. Node: Control Letters162121
  17771. Node: Format Modifiers164809
  17772. Node: Printf Examples168958
  17773. Node: Redirection171736
  17774. Node: Special Files176375
  17775. Node: Close Files And Pipes181612
  17776. Node: Expressions185672
  17777. Node: Constants187868
  17778. Node: Scalar Constants188347
  17779. Node: Regexp Constants189352
  17780. Node: Using Constant Regexps189814
  17781. Node: Variables193015
  17782. Node: Using Variables193669
  17783. Node: Assignment Options195104
  17784. Node: Conversion197049
  17785. Node: Arithmetic Ops200231
  17786. Node: Concatenation202365
  17787. Node: Assignment Ops203720
  17788. Node: Increment Ops209316
  17789. Node: Truth Values211844
  17790. Node: Typing and Comparison212892
  17791. Node: Boolean Ops218792
  17792. Node: Conditional Exp222485
  17793. Node: Function Calls224162
  17794. Node: Precedence227044
  17795. Node: Patterns and Actions230432
  17796. Node: Pattern Overview230858
  17797. Node: Kinds of Patterns231633
  17798. Node: Regexp Patterns232770
  17799. Node: Expression Patterns233324
  17800. Node: Ranges236975
  17801. Node: BEGIN/END239694
  17802. Node: Using BEGIN/END240163
  17803. Node: I/O And BEGIN/END243126
  17804. Node: Empty245142
  17805. Node: Action Overview245441
  17806. Node: Statements248013
  17807. Node: If Statement249719
  17808. Node: While Statement251222
  17809. Node: Do Statement253252
  17810. Node: For Statement254354
  17811. Node: Break Statement257611
  17812. Node: Continue Statement259882
  17813. Node: Next Statement261878
  17814. Node: Nextfile Statement264161
  17815. Node: Exit Statement266075
  17816. Node: Built-in Variables268085
  17817. Node: User-modified269181
  17818. Node: Auto-set273902
  17819. Node: ARGC and ARGV280432
  17820. Node: Arrays283134
  17821. Node: Array Intro284597
  17822. Node: Reference to Elements288473
  17823. Node: Assigning Elements290423
  17824. Node: Array Example290925
  17825. Node: Scanning an Array292644
  17826. Node: Delete294974
  17827. Node: Numeric Array Subscripts297033
  17828. Node: Uninitialized Subscripts298939
  17829. Node: Multi-dimensional300579
  17830. Node: Multi-scanning303674
  17831. Node: Built-in305317
  17832. Node: Calling Built-in306306
  17833. Node: Numeric Functions308277
  17834. Node: String Functions312096
  17835. Node: I/O Functions330437
  17836. Node: Time Functions334998
  17837. Node: User-defined343861
  17838. Node: Definition Syntax344574
  17839. Node: Function Example348823
  17840. Node: Function Caveats351152
  17841. Node: Return Statement354819
  17842. Node: Invoking Gawk357474
  17843. Node: Options358709
  17844. Node: Other Arguments367572
  17845. Node: AWKPATH Variable370220
  17846. Node: Obsolete372969
  17847. Node: Undocumented373633
  17848. Node: Known Bugs373841
  17849. Node: Library Functions375067
  17850. Node: Portability Notes377358
  17851. Node: Nextfile Function378642
  17852. Node: Assert Function383518
  17853. Node: Ordinal Functions387216
  17854. Node: Join Function390669
  17855. Node: Mktime Function392721
  17856. Node: Gettimeofday Function404294
  17857. Node: Filetrans Function408306
  17858. Node: Getopt Function411983
  17859. Node: Passwd Functions423339
  17860. Node: Group Functions431614
  17861. Node: Library Names439511
  17862. Node: Sample Programs443436
  17863. Node: Clones443927
  17864. Node: Cut Program445021
  17865. Node: Egrep Program455039
  17866. Node: Id Program462346
  17867. Node: Split Program465617
  17868. Node: Tee Program468995
  17869. Node: Uniq Program471791
  17870. Node: Wc Program479337
  17871. Node: Miscellaneous Programs483754
  17872. Node: Dupword Program484664
  17873. Node: Alarm Program486335
  17874. Node: Translate Program490879
  17875. Node: Labels Program495691
  17876. Node: Word Sorting499235
  17877. Node: History Sorting503580
  17878. Node: Extract Program505549
  17879. Node: Simple Sed512506
  17880. Node: Igawk Program515850
  17881. Node: Language History528993
  17882. Node: V7/SVR3.1530231
  17883. Node: SVR4532886
  17884. Node: POSIX534408
  17885. Node: BTL535926
  17886. Node: POSIX/GNU536699
  17887. Node: Gawk Summary541131
  17888. Node: Command Line Summary541953
  17889. Node: Language Summary544898
  17890. Node: Variables/Fields547279
  17891. Node: Fields Summary548013
  17892. Node: Built-in Summary549520
  17893. Node: Arrays Summary553165
  17894. Node: Data Type Summary554458
  17895. Node: Rules Summary556284
  17896. Node: Pattern Summary557812
  17897. Node: Regexp Summary559997
  17898. Node: Actions Summary563334
  17899. Node: Operator Summary565166
  17900. Node: Control Flow Summary566393
  17901. Node: I/O Summary566950
  17902. Node: Printf Summary569939
  17903. Node: Special File Summary573277
  17904. Node: Built-in Functions Summary574955
  17905. Node: Time Functions Summary578884
  17906. Node: String Constants Summary579745
  17907. Node: Functions Summary581065
  17908. Node: Historical Features582126
  17909. Node: Installation583624
  17910. Node: Gawk Distribution584839
  17911. Node: Getting585342
  17912. Node: Extracting588312
  17913. Node: Distribution contents589699
  17914. Node: Unix Installation594100
  17915. Node: Quick Installation594609
  17916. Node: Configuration Philosophy596127
  17917. Node: VMS Installation598529
  17918. Node: VMS Compilation599068
  17919. Node: VMS Installation Details600672
  17920. Node: VMS Running602314
  17921. Node: VMS POSIX603904
  17922. Node: PC Installation605103
  17923. Node: Atari Installation608479
  17924. Node: Atari Compiling609663
  17925. Node: Atari Using611572
  17926. Node: Amiga Installation614419
  17927. Node: Bugs615448
  17928. Node: Other Versions618416
  17929. Node: Notes619823
  17930. Node: Compatibility Mode620430
  17931. Node: Additions621273
  17932. Node: Adding Code621971
  17933. Node: New Ports627066
  17934. Node: Future Extensions631234
  17935. Node: Improvements633659
  17936. Node: Glossary635527
  17937. Node: Copying652582
  17938. Node: Index671774
  17939. 
  17940. End Tag Table
  17941.